/
index.js
417 lines (363 loc) · 12.1 KB
/
index.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
var Accessor = require('../accessor');
var React = require('react');
var TypeaheadSelector = require('./selector');
var KeyEvent = require('../keyevent');
var fuzzy = require('fuzzy');
var classNames = require('classnames');
var createReactClass = require('create-react-class');
var PropTypes = require('prop-types');
/**
* A "typeahead", an auto-completing text input
*
* Renders an text input that shows options nearby that you can use the
* keyboard or mouse to select. Requires CSS for MASSIVE DAMAGE.
*/
var Typeahead = createReactClass({
propTypes: {
name: PropTypes.string,
customClasses: PropTypes.object,
maxVisible: PropTypes.number,
resultsTruncatedMessage: PropTypes.string,
options: PropTypes.array,
allowCustomValues: PropTypes.number,
initialValue: PropTypes.string,
value: PropTypes.string,
placeholder: PropTypes.string,
disabled: PropTypes.bool,
textarea: PropTypes.bool,
inputProps: PropTypes.object,
onOptionSelected: PropTypes.func,
onChange: PropTypes.func,
onKeyDown: PropTypes.func,
onKeyPress: PropTypes.func,
onKeyUp: PropTypes.func,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
filterOption: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func
]),
searchOptions: PropTypes.func,
displayOption: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func
]),
inputDisplayOption: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func
]),
formInputOption: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func
]),
defaultClassNames: PropTypes.bool,
customListComponent: PropTypes.oneOfType([
PropTypes.element,
PropTypes.func
]),
showOptionsWhenEmpty: PropTypes.bool
},
getDefaultProps: function() {
return {
options: [],
customClasses: {},
allowCustomValues: 0,
initialValue: "",
value: "",
placeholder: "",
disabled: false,
textarea: false,
inputProps: {},
onOptionSelected: function(option) {},
onChange: function(event) {},
onKeyDown: function(event) {},
onKeyPress: function(event) {},
onKeyUp: function(event) {},
onFocus: function(event) {},
onBlur: function(event) {},
filterOption: null,
searchOptions: null,
inputDisplayOption: null,
defaultClassNames: true,
customListComponent: TypeaheadSelector,
showOptionsWhenEmpty: false,
resultsTruncatedMessage: null
};
},
getInitialState: function() {
return {
// The options matching the entry value
searchResults: this.getOptionsForValue(this.props.initialValue, this.props.options),
// This should be called something else, "entryValue"
entryValue: this.props.value || this.props.initialValue,
// A valid typeahead value
selection: this.props.value,
// Index of the selection
selectionIndex: null,
// Keep track of the focus state of the input element, to determine
// whether to show options when empty (if showOptionsWhenEmpty is true)
isFocused: false,
// true when focused, false onOptionSelected
showResults: false
};
},
_shouldSkipSearch: function(input) {
var emptyValue = !input || input.trim().length == 0;
// this.state must be checked because it may not be defined yet if this function
// is called from within getInitialState
var isFocused = this.state && this.state.isFocused;
return !(this.props.showOptionsWhenEmpty && isFocused) && emptyValue;
},
getOptionsForValue: function(value, options) {
if (this._shouldSkipSearch(value)) { return []; }
var searchOptions = this._generateSearchFunction();
return searchOptions(value, options);
},
setEntryText: function(value) {
this.refs.entry.value = value;
this._onTextEntryUpdated();
},
focus: function(){
this.refs.entry.focus()
},
_hasCustomValue: function() {
if (this.props.allowCustomValues > 0 &&
this.state.entryValue.length >= this.props.allowCustomValues &&
this.state.searchResults.indexOf(this.state.entryValue) < 0) {
return true;
}
return false;
},
_getCustomValue: function() {
if (this._hasCustomValue()) {
return this.state.entryValue;
}
return null;
},
_renderIncrementalSearchResults: function() {
// Nothing has been entered into the textbox
if (this._shouldSkipSearch(this.state.entryValue)) {
return "";
}
// Something was just selected
if (this.state.selection) {
return "";
}
return (
<this.props.customListComponent
ref="sel" options={this.props.maxVisible ? this.state.searchResults.slice(0, this.props.maxVisible) : this.state.searchResults}
areResultsTruncated={this.props.maxVisible && this.state.searchResults.length > this.props.maxVisible}
resultsTruncatedMessage={this.props.resultsTruncatedMessage}
onOptionSelected={this._onOptionSelected}
allowCustomValues={this.props.allowCustomValues}
customValue={this._getCustomValue()}
customClasses={this.props.customClasses}
selectionIndex={this.state.selectionIndex}
defaultClassNames={this.props.defaultClassNames}
displayOption={Accessor.generateOptionToStringFor(this.props.displayOption)} />
);
},
getSelection: function() {
var index = this.state.selectionIndex;
if (this._hasCustomValue()) {
if (index === 0) {
return this.state.entryValue;
} else {
index--;
}
}
return this.state.searchResults[index];
},
_onOptionSelected: function(option, event) {
var nEntry = this.refs.entry;
nEntry.focus();
var displayOption = Accessor.generateOptionToStringFor(this.props.inputDisplayOption || this.props.displayOption);
var optionString = displayOption(option, 0);
var formInputOption = Accessor.generateOptionToStringFor(this.props.formInputOption || displayOption);
var formInputOptionString = formInputOption(option);
nEntry.value = optionString;
this.setState({searchResults: this.getOptionsForValue(optionString, this.props.options),
selection: formInputOptionString,
entryValue: optionString,
showResults: false});
return this.props.onOptionSelected(option, event);
},
_onTextEntryUpdated: function() {
var value = this.refs.entry.value;
this.setState({searchResults: this.getOptionsForValue(value, this.props.options),
selection: '',
entryValue: value});
},
_onEnter: function(event) {
var selection = this.getSelection();
if (!selection) {
return this.props.onKeyDown(event);
}
return this._onOptionSelected(selection, event);
},
_onEscape: function() {
this.setState({
selectionIndex: null
});
},
_onTab: function(event) {
var selection = this.getSelection();
var option = selection ?
selection : (this.state.searchResults.length > 0 ? this.state.searchResults[0] : null);
if (option === null && this._hasCustomValue()) {
option = this._getCustomValue();
}
if (option !== null) {
return this._onOptionSelected(option, event);
}
},
eventMap: function(event) {
var events = {};
events[KeyEvent.DOM_VK_UP] = this.navUp;
events[KeyEvent.DOM_VK_DOWN] = this.navDown;
events[KeyEvent.DOM_VK_RETURN] = events[KeyEvent.DOM_VK_ENTER] = this._onEnter;
events[KeyEvent.DOM_VK_ESCAPE] = this._onEscape;
events[KeyEvent.DOM_VK_TAB] = this._onTab;
return events;
},
_nav: function(delta) {
if (!this._hasHint()) {
return;
}
var newIndex = this.state.selectionIndex === null ? (delta == 1 ? 0 : delta) : this.state.selectionIndex + delta;
var length = this.props.maxVisible ? this.state.searchResults.slice(0, this.props.maxVisible).length : this.state.searchResults.length;
if (this._hasCustomValue()) {
length += 1;
}
if (newIndex < 0) {
newIndex += length;
} else if (newIndex >= length) {
newIndex -= length;
}
this.setState({selectionIndex: newIndex});
},
navDown: function() {
this._nav(1);
},
navUp: function() {
this._nav(-1);
},
_onChange: function(event) {
if (this.props.onChange) {
this.props.onChange(event);
}
this._onTextEntryUpdated();
},
_onKeyDown: function(event) {
// If there are no visible elements, don't perform selector navigation.
// Just pass this up to the upstream onKeydown handler.
// Also skip if the user is pressing the shift key, since none of our handlers are looking for shift
if (!this._hasHint() || event.shiftKey) {
return this.props.onKeyDown(event);
}
var handler = this.eventMap()[event.keyCode];
if (handler) {
handler(event);
} else {
return this.props.onKeyDown(event);
}
// Don't propagate the keystroke back to the DOM/browser
event.preventDefault();
},
componentWillReceiveProps: function(nextProps) {
var searchResults = this.getOptionsForValue(this.state.entryValue, nextProps.options);
var showResults = Boolean(searchResults.length) && this.state.isFocused;
this.setState({
searchResults: searchResults,
showResults: showResults
});
},
render: function() {
var inputClasses = {};
inputClasses[this.props.customClasses.input] = !!this.props.customClasses.input;
var inputClassList = classNames(inputClasses);
var classes = {
typeahead: this.props.defaultClassNames
};
classes[this.props.className] = !!this.props.className;
var classList = classNames(classes);
var InputElement = this.props.textarea ? 'textarea' : 'input';
return (
<div className={classList}>
{ this._renderHiddenInput() }
<InputElement ref="entry" type="text"
disabled={this.props.disabled}
{...this.props.inputProps}
placeholder={this.props.placeholder}
className={inputClassList}
value={this.state.entryValue}
onChange={this._onChange}
onKeyDown={this._onKeyDown}
onKeyPress={this.props.onKeyPress}
onKeyUp={this.props.onKeyUp}
onFocus={this._onFocus}
onBlur={this._onBlur}
/>
{ this.state.showResults && this._renderIncrementalSearchResults() }
</div>
);
},
_onFocus: function(event) {
this.setState({isFocused: true, showResults: true}, function () {
this._onTextEntryUpdated();
}.bind(this));
if ( this.props.onFocus ) {
return this.props.onFocus(event);
}
},
_onBlur: function(event) {
this.setState({isFocused: false}, function () {
this._onTextEntryUpdated();
}.bind(this));
if ( this.props.onBlur ) {
return this.props.onBlur(event);
}
},
_renderHiddenInput: function() {
if (!this.props.name) {
return null;
}
return (
<input
type="hidden"
name={ this.props.name }
value={ this.state.selection }
/>
);
},
_generateSearchFunction: function() {
var searchOptionsProp = this.props.searchOptions;
var filterOptionProp = this.props.filterOption;
if (typeof searchOptionsProp === 'function') {
if (filterOptionProp !== null) {
console.warn('searchOptions prop is being used, filterOption prop will be ignored');
}
return searchOptionsProp;
} else if (typeof filterOptionProp === 'function') {
return function(value, options) {
return options.filter(function(o) { return filterOptionProp(value, o); });
};
} else {
var mapper;
if (typeof filterOptionProp === 'string') {
mapper = Accessor.generateAccessor(filterOptionProp);
} else {
mapper = Accessor.IDENTITY_FN;
}
return function(value, options) {
return fuzzy
.filter(value, options, {extract: mapper})
.map(function(res) { return options[res.index]; });
};
}
},
_hasHint: function() {
return this.state.searchResults.length > 0 || this._hasCustomValue();
}
});
module.exports = Typeahead;