forked from input-output-hk/react-polymorph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutocomplete.js
More file actions
316 lines (273 loc) · 9 KB
/
Autocomplete.js
File metadata and controls
316 lines (273 loc) · 9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// @flow
import React, { Component } from 'react';
import type { ComponentType, Element } from 'react';
// external libraries
import createRef from 'create-react-ref/lib/createRef';
import _ from 'lodash';
// interal components
import { GlobalListeners } from './HOC/GlobalListeners';
import { withTheme } from './HOC/withTheme';
// internal utility functions
import { composeTheme, addThemeId, didThemePropsChange } from '../utils/themes';
import { composeFunctions } from '../utils/props';
import { IDENTIFIERS } from '../themes/API';
type Props = {
className: string,
context: {
theme: Object,
ROOT_THEME_API: Object
},
error: string,
invalidCharsRegex: RegExp,
isOpeningUpward: boolean,
label: string | Element<any>,
maxSelections: number,
maxVisibleOptions: number,
multipleSameSelections: boolean,
onChange: Function,
options: Array<any>,
preselectedOptions: Array<any>,
placeholder: string,
renderSelections: Function,
renderOptions: Function,
skin: ComponentType<any>,
sortAlphabetically: boolean,
theme: Object, // will take precedence over theme in context if passed
themeId: string,
themeOverrides: Object
};
type State = {
inputValue: string,
error: string,
selectedOptions: Array<any>,
filteredOptions: Array<any>,
isOpen: boolean,
composedTheme: Object
};
class AutocompleteBase extends Component<Props, State> {
rootElement: ?Element<any>;
inputElement: ?Element<'input'>;
suggestionsElement: ?Element<any>;
optionsElement: ?Element<any>;
static defaultProps = {
error: null,
invalidCharsRegex: /[^a-zA-Z0-9]/g, // only allow letters and numbers by default
isOpeningUpward: false,
maxVisibleOptions: 10, // max number of visible options
multipleSameSelections: true, // if true then same word can be selected multiple times
options: [],
sortAlphabetically: true, // options are sorted alphabetically by default
theme: null,
themeId: IDENTIFIERS.AUTOCOMPLETE,
themeOverrides: {}
};
constructor(props: Props) {
super(props);
// define refs
this.rootElement = createRef();
this.inputElement = createRef();
this.suggestionsElement = createRef();
this.optionsElement = createRef();
const {
context,
themeId,
theme,
themeOverrides,
sortAlphabetically,
options,
preselectedOptions
} = props;
this.state = {
inputValue: '',
error: '',
selectedOptions: preselectedOptions || [],
filteredOptions:
sortAlphabetically && options ? options.sort() : options || [],
isOpen: false,
composedTheme: composeTheme(
addThemeId(theme || context.theme, themeId),
addThemeId(themeOverrides, themeId),
context.ROOT_THEME_API
)
};
}
componentWillReceiveProps(nextProps: Props) {
didThemePropsChange(this.props, nextProps, this.setState.bind(this));
}
clear = () => this._removeOptions();
focus = () => this.handleAutocompleteClick();
open = () => this.setState({ isOpen: true });
close = () => this.setState({ isOpen: false });
toggleOpen = () => this.setState({ isOpen: !this.state.isOpen });
handleAutocompleteClick = () => {
const { inputElement } = this;
if (inputElement && inputElement.current) {
inputElement.current.focus();
}
// toggle options open/closed
this.toggleOpen();
};
onKeyDown = (event: SyntheticKeyboardEvent<>) => {
if ( // Check for backspace in order to delete the last selected option
event.keyCode === 8 &&
!event.target.value &&
this.state.selectedOptions.length
) {
// Remove last selected option
this.removeOption(this.state.selectedOptions.length - 1, event);
} else if (event.keyCode === 27) { // ESCAPE key: Stops propagation & modal closing
event.stopPropagation();
} else if (event.keyCode === 13) { // ENTER key: Opens suggestions
this.open();
}
};
// onChange handler for input element in AutocompleteSkin
handleInputChange = (event: SyntheticInputEvent<HTMLInputElement>) => {
this._setInputValue(event.target.value);
};
// passed to Options onChange handler in AutocompleteSkin
handleChange = (option: any, event: SyntheticEvent<>) => {
this.updateSelectedOptions(event, option);
};
updateSelectedOptions = (
event: SyntheticEvent<>,
selectedOption: any = null
) => {
const canMoreOptionsBeSelected =
this.state.selectedOptions.length < this.props.maxSelections;
const areFilteredOptionsAvailable =
this.state.filteredOptions && this.state.filteredOptions.length > 0;
if (
!this.props.maxSelections ||
(canMoreOptionsBeSelected && areFilteredOptionsAvailable)
) {
if (!selectedOption) return;
const option = selectedOption.trim();
const optionCanBeSelected =
(this.state.selectedOptions.indexOf(option) < 0 &&
!this.props.multipleSameSelections) ||
this.props.multipleSameSelections;
if (option && optionCanBeSelected && this.state.isOpen) {
const selectedOptions = _.concat(this.state.selectedOptions, option);
this.selectionChanged(selectedOptions, event);
this.setState({ selectedOptions, isOpen: false });
}
}
this._setInputValue('');
};
removeOption = (index: number, event: SyntheticEvent<>) => {
const selectedOptions = this.state.selectedOptions;
_.pullAt(selectedOptions, index);
this.selectionChanged(selectedOptions, event);
this.setState({ selectedOptions });
};
selectionChanged = (
selectedOptions: Array<any>,
event: SyntheticEvent<any>
) => {
if (this.props.onChange) this.props.onChange(selectedOptions, event);
};
// returns an object containing props, theme, and method handlers
// associated with rendering this.state.selectedOptions, the user can call
// this in the body of the renderSelections function
getSelectionProps = ({
removeSelection
}: { removeSelection: Function } = {}) => {
const { themeId } = this.props;
const { inputValue, isOpen, selectedOptions, composedTheme } = this.state;
return {
inputValue,
isOpen,
selectedOptions,
theme: composedTheme[themeId],
removeSelection: (index: number, event: SyntheticEvent<>) =>
// the user's custom removeSelection event handler is composed with
// the internal functionality of Autocomplete (this.removeOption)
composeFunctions(removeSelection, this.removeOption)(index, event)
};
};
render() {
// destructuring props ensures only the "...rest" get passed down
const {
context,
invalidCharsRegex,
multipleSameSelections,
sortAlphabetically,
skin: AutocompleteSkin,
theme,
themeOverrides,
onChange,
error,
...rest
} = this.props;
return (
<GlobalListeners
optionsIsOpen={this.state.isOpen}
optionsRef={this.optionsElement}
rootRef={this.rootElement}
toggleOpen={this.toggleOpen}
>
{() => (
<AutocompleteSkin
error={error || this.state.error}
filteredOptions={this.state.filteredOptions}
getSelectionProps={this.getSelectionProps}
handleAutocompleteClick={this.handleAutocompleteClick}
handleChange={this.handleChange}
handleInputChange={this.handleInputChange}
inputRef={this.inputElement}
inputValue={this.state.inputValue}
isOpen={this.state.isOpen}
onKeyDown={this.onKeyDown}
optionsRef={this.optionsElement}
removeOption={this.removeOption}
rootRef={this.rootElement}
selectedOptions={this.state.selectedOptions}
suggestionsRef={this.suggestionsElement}
theme={this.state.composedTheme}
toggleOpen={this.toggleOpen}
{...rest}
/>
)}
</GlobalListeners>
);
}
// ======== PRIVATE METHOD ==========
_removeOptions = () => {
const { onChange } = this.props;
onChange ? onChange([]) : null;
this.setState({ selectedOptions: [], inputValue: '' });
};
_filterOptions = (value: string) => {
let filteredOptions = [];
if (value !== '') {
_.some(this.props.options, (option) => {
if (_.startsWith(option, value)) {
filteredOptions.push(option);
}
});
} else {
filteredOptions = this.props.options;
}
return filteredOptions;
};
_filterInvalidChars = (value: string) => {
let filteredValue = '';
if (this.props.invalidCharsRegex.test(value)) {
filteredValue = value.replace(this.props.invalidCharsRegex, '');
} else {
filteredValue = value;
}
return filteredValue;
};
_setInputValue = (value: string) => {
const filteredValue = this._filterInvalidChars(value);
const filteredOptions = this._filterOptions(filteredValue);
this.setState({
isOpen: true,
inputValue: filteredValue,
filteredOptions
});
}
}
export const Autocomplete = withTheme(AutocompleteBase);