forked from moroshko/react-autosuggest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAutosuggest.js
597 lines (502 loc) · 19.8 KB
/
Autosuggest.js
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
import React, { Component, PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import debounce from 'debounce';
import themeable from 'react-themeable';
import sectionIterator from './sectionIterator';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
export default class Autosuggest extends Component {
static propTypes = {
value: PropTypes.string, // Controlled value of the selected suggestion
defaultValue: PropTypes.string, // Initial value of the text
suggestions: PropTypes.func.isRequired, // Function to get the suggestions
suggestionRenderer: PropTypes.func, // Function that renders a given suggestion (must be implemented when suggestions are objects)
suggestionValue: PropTypes.func, // Function that maps suggestion object to input value (must be implemented when suggestions are objects)
showWhen: PropTypes.func, // Function that determines whether to show suggestions or not
onSuggestionSelected: PropTypes.func, // This function is called when suggestion is selected via mouse click or Enter
onSuggestionFocused: PropTypes.func, // This function is called when suggestion is focused via mouse hover or Up/Down keys
onSuggestionUnfocused: PropTypes.func, // This function is called when suggestion is unfocused via mouse hover or Up/Down keys
inputAttributes: PropTypes.object, // Attributes to pass to the input field (e.g. { id: 'my-input', className: 'sweet autosuggest' })
cache: PropTypes.bool, // Set it to false to disable in-memory caching
id: PropTypes.string, // Used in aria-* attributes. If multiple Autosuggest's are rendered on a page, they must have unique ids.
scrollBar: PropTypes.bool, // Set it to true when the suggestions container can have a scroll bar
theme: PropTypes.object // Custom theme. See: https://github.com/markdalgleish/react-themeable
}
static defaultProps = {
showWhen: input => input.trim().length > 0,
onSuggestionSelected: () => {},
onSuggestionFocused: () => {},
onSuggestionUnfocused: () => {},
inputAttributes: {},
cache: true,
id: '1',
scrollBar: false,
theme: {
root: 'react-autosuggest',
suggestions: 'react-autosuggest__suggestions',
suggestion: 'react-autosuggest__suggestion',
suggestionIsFocused: 'react-autosuggest__suggestion--focused',
section: 'react-autosuggest__suggestions-section',
sectionName: 'react-autosuggest__suggestions-section-name',
sectionSuggestions: 'react-autosuggest__suggestions-section-suggestions'
}
}
constructor(props) {
super();
this.cache = {};
this.state = {
value: props.value || props.defaultValue || '',
suggestions: null,
focusedSectionIndex: null, // Used when multiple sections are displayed
focusedSuggestionIndex: null, // Index within a section
valueBeforeUpDown: null // When user interacts using the Up and Down keys,
// this field remembers input's value prior to
// interaction in order to revert back if ESC hit.
// See: http://www.w3.org/TR/wai-aria-practices/#autocomplete
};
this.isControlledComponent = (typeof props.value !== 'undefined');
this.updateProps(props);
this.lastSuggestionsInputValue = null; // Helps to deal with delayed requests
this.justUnfocused = false; // Helps to avoid calling onSuggestionUnfocused
// twice when mouse is moving between suggestions
this.justClickedOnSuggestion = false; // Helps not to call inputAttributes.onBlur
// and showSuggestions() when suggestion is clicked.
// Also helps not to call handleValueChange() in
// componentWillReceiveProps() when suggestion is clicked.
this.justPressedUpDown = false; // Helps not to call handleValueChange() in
// componentWillReceiveProps() when Up or Down is pressed.
this.justPressedEsc = false; // Helps not to call handleValueChange() in
// componentWillReceiveProps() when ESC is pressed.
this.onInputChange = ::this.onInputChange;
this.onInputKeyDown = ::this.onInputKeyDown;
this.onInputFocus = ::this.onInputFocus;
this.onInputBlur = ::this.onInputBlur;
}
updateProps(nextProps) {
this.suggestionsFn = debounce(nextProps.suggestions, 100);
this.onChange = nextProps.inputAttributes.onChange || (() => {});
this.onFocus = nextProps.inputAttributes.onFocus || (() => {});
this.onBlur = nextProps.inputAttributes.onBlur || (() => {});
}
componentWillReceiveProps(nextProps) {
if (this.isControlledComponent) {
const inputValue = findDOMNode(this.refs.input).value;
if (nextProps.value !== inputValue &&
!this.justClickedOnSuggestion && !this.justPressedUpDown && !this.justPressedEsc) {
this.handleValueChange(nextProps.value);
}
}
this.updateProps(nextProps);
}
resetSectionIterator(suggestions) {
if (this.isMultipleSections(suggestions)) {
sectionIterator.setData(suggestions.map(suggestion => suggestion.suggestions.length));
} else {
sectionIterator.setData(suggestions === null ? [] : suggestions.length);
}
}
isMultipleSections(suggestions) {
return suggestions !== null &&
suggestions.length > 0 &&
typeof suggestions[0].suggestions !== 'undefined';
}
setSuggestionsState(suggestions) {
this.resetSectionIterator(suggestions);
this.setState({
suggestions: suggestions,
focusedSectionIndex: null,
focusedSuggestionIndex: null,
valueBeforeUpDown: null
});
}
suggestionsExist(suggestions) {
if (this.isMultipleSections(suggestions)) {
return suggestions.some(section => section.suggestions.length > 0);
}
return suggestions !== null && suggestions.length > 0;
}
showSuggestions(input) {
const cacheKey = input.toLowerCase();
this.lastSuggestionsInputValue = input;
if (!this.props.showWhen(input)) {
this.setSuggestionsState(null);
} else if (this.props.cache && this.cache[cacheKey]) {
this.setSuggestionsState(this.cache[cacheKey]);
} else {
this.suggestionsFn(input, (error, suggestions) => {
// If input value changed, suggestions are not relevant anymore.
if (this.lastSuggestionsInputValue !== input) {
return;
}
if (error) {
throw error;
} else {
if (!this.suggestionsExist(suggestions)) {
suggestions = null;
}
if (this.props.cache) {
this.cache[cacheKey] = suggestions;
}
this.setSuggestionsState(suggestions);
}
});
}
}
suggestionIsFocused() {
return this.state.focusedSuggestionIndex !== null;
}
getSuggestion(sectionIndex, suggestionIndex) {
if (this.isMultipleSections(this.state.suggestions)) {
return this.state.suggestions[sectionIndex].suggestions[suggestionIndex];
}
return this.state.suggestions[suggestionIndex];
}
getFocusedSuggestion() {
if (this.suggestionIsFocused()) {
return this.getSuggestion(this.state.focusedSectionIndex,
this.state.focusedSuggestionIndex);
}
return null;
}
getSuggestionValue(sectionIndex, suggestionIndex) {
const suggestion = this.getSuggestion(sectionIndex, suggestionIndex);
if (typeof suggestion === 'object') {
if (this.props.suggestionValue) {
return this.props.suggestionValue(suggestion);
}
throw new Error('When <suggestion> is an object, you must implement the suggestionValue() function to specify how to set input\'s value when suggestion selected.');
} else {
return suggestion.toString();
}
}
onSuggestionUnfocused() {
const focusedSuggestion = this.getFocusedSuggestion();
if (focusedSuggestion !== null && !this.justUnfocused) {
this.props.onSuggestionUnfocused(focusedSuggestion);
this.justUnfocused = true;
}
}
onSuggestionFocused(sectionIndex, suggestionIndex) {
this.onSuggestionUnfocused();
const suggestion = this.getSuggestion(sectionIndex, suggestionIndex);
this.props.onSuggestionFocused(suggestion);
this.justUnfocused = false;
}
scrollToElement(container, element, alignTo) {
if (alignTo === 'bottom') {
const scrollDelta = element.offsetTop +
element.offsetHeight -
container.scrollTop -
container.offsetHeight;
if (scrollDelta > 0) {
container.scrollTop += scrollDelta;
}
} else {
const scrollDelta = container.scrollTop -
element.offsetTop;
if (scrollDelta > 0) {
container.scrollTop -= scrollDelta;
}
}
}
scrollToSuggestion(direction, sectionIndex, suggestionIndex) {
let alignTo = (direction === 'down' ? 'bottom' : 'top');
if (suggestionIndex === null) {
if (direction === 'down') {
alignTo = 'top';
[sectionIndex, suggestionIndex] = sectionIterator.next([null, null]);
} else {
return;
}
} else {
if (sectionIterator.isLast([sectionIndex, suggestionIndex]) &&
direction === 'up') {
alignTo = 'bottom';
}
}
const suggestions = findDOMNode(this.refs.suggestions);
const suggestionRef = this.getSuggestionRef(sectionIndex, suggestionIndex);
const suggestion = findDOMNode(this.refs[suggestionRef]);
this.scrollToElement(suggestions, suggestion, alignTo);
}
focusOnSuggestionUsingKeyboard(direction, suggestionPosition) {
const [sectionIndex, suggestionIndex] = suggestionPosition;
const newState = {
focusedSectionIndex: sectionIndex,
focusedSuggestionIndex: suggestionIndex,
value: suggestionIndex === null
? this.state.valueBeforeUpDown
: this.getSuggestionValue(sectionIndex, suggestionIndex)
};
this.justPressedUpDown = true;
// When users starts to interact with Up/Down keys, remember input's value.
if (this.state.valueBeforeUpDown === null) {
newState.valueBeforeUpDown = this.state.value;
}
if (suggestionIndex === null) {
this.onSuggestionUnfocused();
} else {
this.onSuggestionFocused(sectionIndex, suggestionIndex);
}
if (this.props.scrollBar) {
this.scrollToSuggestion(direction, sectionIndex, suggestionIndex);
}
if (newState.value !== this.state.value) {
this.onChange(newState.value);
}
this.setState(newState);
setTimeout(() => this.justPressedUpDown = false);
}
onSuggestionSelected(event) {
let focusedSuggestion = this.getFocusedSuggestion(); // Required when Enter is pressed
if (focusedSuggestion === null) {
// We are on a mobile device
const sectionIndex = event.target.getAttribute('data-section-index');
const touchedSectionIndex = (typeof sectionIndex === 'string' ? +sectionIndex : null);
const touchedSuggestionIndex = +event.target.getAttribute('data-suggestion-index');
focusedSuggestion =
this.getSuggestion(touchedSectionIndex, touchedSuggestionIndex);
}
this.props.onSuggestionUnfocused(focusedSuggestion);
this.props.onSuggestionSelected(focusedSuggestion, event);
}
onInputChange(event) {
const newValue = event.target.value;
this.onSuggestionUnfocused();
this.handleValueChange(newValue);
this.showSuggestions(newValue);
}
handleValueChange(newValue) {
if (newValue !== this.state.value) {
this.onChange(newValue);
this.setState({
value: newValue
});
}
}
onInputKeyDown(event) {
let newState;
switch (event.keyCode) {
case 13: // Enter
if (this.state.valueBeforeUpDown !== null && this.suggestionIsFocused()) {
this.onSuggestionSelected(event);
}
this.setSuggestionsState(null);
break;
case 27: // ESC
newState = {
suggestions: null,
focusedSectionIndex: null,
focusedSuggestionIndex: null,
valueBeforeUpDown: null
};
if (this.state.valueBeforeUpDown !== null) {
newState.value = this.state.valueBeforeUpDown;
} else if (this.state.suggestions === null) {
newState.value = '';
}
this.onSuggestionUnfocused();
this.justPressedEsc = true;
if (typeof newState.value === 'string' && newState.value !== this.state.value) {
this.onChange(newState.value);
}
this.setState(newState);
setTimeout(() => this.justPressedEsc = false);
break;
case 38: // Up
if (this.state.suggestions === null) {
this.showSuggestions(this.state.value);
} else {
this.focusOnSuggestionUsingKeyboard(
'up',
sectionIterator.prev([this.state.focusedSectionIndex,
this.state.focusedSuggestionIndex])
);
}
event.preventDefault(); // Prevent the cursor from jumping to input's start
break;
case 40: // Down
if (this.state.suggestions === null) {
this.showSuggestions(this.state.value);
} else {
this.focusOnSuggestionUsingKeyboard(
'down',
sectionIterator.next([this.state.focusedSectionIndex,
this.state.focusedSuggestionIndex])
);
}
break;
}
}
onInputFocus(event) {
if (!this.justClickedOnSuggestion) {
this.showSuggestions(this.state.value);
}
this.onFocus(event);
}
onInputBlur(event) {
this.onSuggestionUnfocused();
if (!this.justClickedOnSuggestion) {
this.onBlur(event);
}
this.setSuggestionsState(null);
}
isSuggestionFocused(sectionIndex, suggestionIndex) {
return sectionIndex === this.state.focusedSectionIndex &&
suggestionIndex === this.state.focusedSuggestionIndex;
}
onSuggestionMouseEnter(sectionIndex, suggestionIndex) {
if (!this.isSuggestionFocused(sectionIndex, suggestionIndex)) {
this.onSuggestionFocused(sectionIndex, suggestionIndex);
}
this.setState({
focusedSectionIndex: sectionIndex,
focusedSuggestionIndex: suggestionIndex
});
}
onSuggestionMouseLeave(sectionIndex, suggestionIndex) {
if (this.isSuggestionFocused(sectionIndex, suggestionIndex)) {
this.onSuggestionUnfocused();
}
this.setState({
focusedSectionIndex: null,
focusedSuggestionIndex: null
});
}
onSuggestionClick(sectionIndex, suggestionIndex, event) {
const suggestionValue = this.getSuggestionValue(sectionIndex, suggestionIndex);
this.justClickedOnSuggestion = true;
this.onSuggestionSelected(event);
if (suggestionValue !== this.state.value) {
this.onChange(suggestionValue);
}
this.setState({
value: suggestionValue,
suggestions: null,
focusedSectionIndex: null,
focusedSuggestionIndex: null,
valueBeforeUpDown: null
}, () => {
// This code executes after the component is re-rendered
setTimeout(() => {
findDOMNode(this.refs.input).focus();
this.justClickedOnSuggestion = false;
});
});
}
getSuggestionId(sectionIndex, suggestionIndex) {
if (suggestionIndex === null) {
return null;
}
return 'react-autosuggest-' + this.props.id + '-' +
this.getSuggestionRef(sectionIndex, suggestionIndex);
}
getSuggestionRef(sectionIndex, suggestionIndex) {
return 'suggestion-' + (sectionIndex === null ? '' : sectionIndex) +
'-' + suggestionIndex;
}
renderSuggestionContent(suggestion) {
if (this.props.suggestionRenderer) {
return this.props.suggestionRenderer(
suggestion,
this.state.valueBeforeUpDown || this.state.value
);
}
if (typeof suggestion === 'object') {
throw new Error('When <suggestion> is an object, you must implement the suggestionRenderer() function to specify how to render it.');
} else {
return suggestion.toString();
}
}
renderSuggestionsList(theme, suggestions, sectionIndex) {
return suggestions.map((suggestion, suggestionIndex) => {
const styles = theme(suggestionIndex, 'suggestion',
sectionIndex === this.state.focusedSectionIndex &&
suggestionIndex === this.state.focusedSuggestionIndex &&
'suggestionIsFocused'
);
const suggestionRef =
this.getSuggestionRef(sectionIndex, suggestionIndex);
const onSuggestionClick = event =>
this.onSuggestionClick(sectionIndex, suggestionIndex, event);
return (
<li id={this.getSuggestionId(sectionIndex, suggestionIndex)}
{...styles}
role="option"
ref={suggestionRef}
key={suggestionRef}
data-section-index={sectionIndex}
data-suggestion-index={suggestionIndex}
onMouseEnter={() => this.onSuggestionMouseEnter(sectionIndex, suggestionIndex)}
onMouseLeave={() => this.onSuggestionMouseLeave(sectionIndex, suggestionIndex)}
onMouseDown={onSuggestionClick}
onTouchTap={onSuggestionClick}>
{this.renderSuggestionContent(suggestion)}
</li>
);
});
}
renderSuggestions(theme) {
if (this.state.suggestions === null) {
return null;
}
if (this.isMultipleSections(this.state.suggestions)) {
return (
<div id={'react-autosuggest-' + this.props.id}
{...theme('suggestions', 'suggestions')}
ref="suggestions"
role="listbox">
{this.state.suggestions.map((section, sectionIndex) => {
const sectionName = section.sectionName ? (
<div {...theme('sectionName-' + sectionIndex, 'sectionName')}>
{section.sectionName}
</div>
) : null;
return section.suggestions.length === 0 ? null : (
<div {...theme('section-' + sectionIndex, 'section')}
key={'section-' + sectionIndex}>
{sectionName}
<ul {...theme('sectionSuggestions-' + sectionIndex, 'sectionSuggestions')}>
{this.renderSuggestionsList(theme, section.suggestions, sectionIndex)}
</ul>
</div>
);
})}
</div>
);
}
return (
<ul id={'react-autosuggest-' + this.props.id}
{...theme('suggestions', 'suggestions')}
ref="suggestions"
role="listbox">
{this.renderSuggestionsList(theme, this.state.suggestions, null)}
</ul>
);
}
render() {
const { id, inputAttributes } = this.props;
const { value, suggestions, focusedSectionIndex, focusedSuggestionIndex } = this.state;
const theme = themeable(this.props.theme);
const ariaActivedescendant = this.getSuggestionId(focusedSectionIndex, focusedSuggestionIndex);
return (
<div {...theme('root', 'root')}>
<input {...inputAttributes}
type={inputAttributes.type || 'text'}
value={value}
autoComplete="off"
role="combobox"
aria-autocomplete="list"
aria-owns={'react-autosuggest-' + id}
aria-expanded={suggestions !== null}
aria-activedescendant={ariaActivedescendant}
ref="input"
onChange={this.onInputChange}
onKeyDown={this.onInputKeyDown}
onFocus={this.onInputFocus}
onBlur={this.onInputBlur} />
{this.renderSuggestions(theme)}
</div>
);
}
}