-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathcombobox.js
500 lines (443 loc) · 13.1 KB
/
combobox.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
var React = require('react');
var guid = 0;
var k = function(){};
var addClass = require('./add-class');
var ComboboxOption = require('./option');
var div = React.createFactory('div');
var span = React.createFactory('span');
var input = React.createFactory('input');
module.exports = React.createClass({
propTypes: {
/**
* Called when the combobox's input receives focus and the user begins interacting with it.
*
* Signature:
*
* ```js
* function(userInput){}
* ```
*/
onFocus: React.PropTypes.func,
/**
* Called when the combobox's input loses focus after being activated for user input
*
* Signature:
*
* ```js
* function(userInput){}
* ```
*/
onBlur: React.PropTypes.func,
/**
* Called when the combobox receives user input, this is your chance to
* filter the data and rerender the options.
*
* Signature:
*
* ```js
* function(userInput){}
* ```
*/
onInput: React.PropTypes.func,
/**
* Called when the combobox receives a selection. You probably want to reset
* the options to the full list at this point.
*
* Signature:
*
* ```js
* function(selectedValue){}
* ```
*/
onSelect: React.PropTypes.func,
/**
* Shown when the combobox is empty.
*/
placeholder: React.PropTypes.string
},
getDefaultProps: function() {
return {
autocomplete: 'both',
onFocus: k,
onBlur: k,
onInput: k,
onSelect: k,
value: null,
showListOnFocus: false
};
},
getInitialState: function() {
return {
value: this.props.value,
// the value displayed in the input
inputValue: this.findInitialInputValue(),
isOpen: false,
focusedIndex: null,
matchedAutocompleteOption: null,
// this prevents crazy jumpiness since we focus options on mouseenter
usingKeyboard: false,
activedescendant: null,
listId: 'ic-tokeninput-list-'+(++guid),
menu: {
children: [],
activedescendant: null,
isEmpty: true
}
};
},
componentWillMount: function() {
this.setState({menu: this.makeMenu(this.props.children)});
},
componentWillReceiveProps: function(newProps) {
this.setState({menu: this.makeMenu(newProps.children)}, function() {
if(newProps.children.length && (this.isOpen || document.activeElement === this.refs.input)) {
if(!this.state.menu.children.length) {
return
}
this.setState({
isOpen: true
}, function() {
this.refs.list.scrollTop = 0;
}.bind(this))
} else {
this.hideList();
}
}.bind(this));
},
/**
* We don't create the <ComboboxOption> components, the user supplies them,
* so before rendering we attach handlers to facilitate communication from
* the ComboboxOption to the Combobox.
*/
makeMenu: function(children) {
var activedescendant;
var isEmpty = true;
// Should this instead use React.addons.cloneWithProps or React.cloneElement?
var _children = React.Children.map(children, function(child, index) {
// console.log(child.type, ComboboxOption.type)
if (child.type !== ComboboxOption || !child.props.isFocusable) {
// allow random elements to live in this list
return child;
}
isEmpty = false;
// TODO: cloneWithProps and map instead of altering the children in-place
var props = child.props;
var newProps = {};
if (this.state.value === child.props.value) {
// need an ID for WAI-ARIA
newProps.id = props.id || 'ic-tokeninput-selected-'+(++guid);
newProps.isSelected = true
activedescendant = props.id;
}
newProps.onBlur = this.handleOptionBlur;
newProps.onClick = this.selectOption.bind(this, child);
newProps.onFocus = this.handleOptionFocus;
newProps.onKeyDown = this.handleOptionKeyDown.bind(this, child);
newProps.onMouseEnter = this.handleOptionMouseEnter.bind(this, index);
return React.cloneElement(child, newProps);
}.bind(this));
return {
children: _children,
activedescendant: activedescendant,
isEmpty: isEmpty
};
},
getClassName: function() {
var className = addClass(this.props.className, 'ic-tokeninput');
if (this.state.isOpen)
className = addClass(className, 'ic-tokeninput-is-open');
return className;
},
/**
* When the user begins typing again we need to clear out any state that has
* to do with an existing or potential selection.
*/
clearSelectedState: function(cb) {
this.setState({
focusedIndex: null,
inputValue: null,
value: null,
matchedAutocompleteOption: null,
activedescendant: null
}, cb);
},
handleInputChange: function() {
var value = this.refs.input.value;
this.clearSelectedState(function() {
this.props.onInput(value);
}.bind(this));
},
handleInputFocus: function() {
this.props.onFocus();
this.maybeShowList();
},
handleInputClick: function() {
this.maybeShowList();
},
maybeShowList: function(){
if (this.props.showListOnFocus){
this.showList()
}
},
handleInputBlur: function() {
var focusedAnOption = this.state.focusedIndex != null;
if (focusedAnOption)
return;
this.maybeSelectAutocompletedOption();
this.hideList();
this.props.onBlur();
},
handleOptionBlur: function() {
// don't want to hide the list if we focused another option
this.blurTimer = setTimeout(this.hideList, 0);
},
handleOptionFocus: function() {
// see `handleOptionBlur`
clearTimeout(this.blurTimer);
},
handleInputKeyUp: function(event) {
if (
this.state.menu.isEmpty ||
// autocompleting while backspacing feels super weird, so let's not
event.keyCode === 8 /*backspace*/ ||
!this.props.autocomplete.match(/both|inline/)
) return;
},
handleButtonClick: function() {
this.state.isOpen ? this.hideList() : this.showList();
this.focusInput();
},
showList: function() {
if(!this.state.menu.children.length) {
return
}
this.setState({isOpen: true})
},
hideList: function() {
this.setState({
isOpen: false,
focusedIndex: null
});
},
hideOnEscape: function(event) {
this.hideList();
this.focusInput();
event.preventDefault();
},
focusInput: function() {
this.refs.input.focus();
},
selectInput: function() {
this.refs.input.select();
},
inputKeydownMap: {
8: 'removeLastToken', // delete
13: 'selectOnEnter', // enter
188: 'selectOnEnter', // comma
27: 'hideOnEscape', // escape
38: 'focusPrevious', // up arrow
40: 'focusNext' // down arrow
},
optionKeydownMap: {
13: 'selectOption',
27: 'hideOnEscape',
38: 'focusPrevious',
40: 'focusNext'
},
handleKeydown: function(event) {
var handlerName = this.inputKeydownMap[event.keyCode];
if (!handlerName)
return
this.setState({usingKeyboard: true});
return this[handlerName].call(this,event);
},
handleOptionKeyDown: function(child, event) {
var handlerName = this.optionKeydownMap[event.keyCode];
if (!handlerName) {
// if the user starts typing again while focused on an option, move focus
// to the inpute, select so it wipes out any existing value
this.selectInput();
return;
}
event.preventDefault();
this.setState({usingKeyboard: true});
this[handlerName].call(this, child);
},
handleOptionMouseEnter: function(index) {
if (this.state.usingKeyboard)
this.setState({usingKeyboard: false});
else
this.focusOptionAtIndex(index);
},
selectOnEnter: function(event) {
event.preventDefault();
this.maybeSelectAutocompletedOption()
},
maybeSelectAutocompletedOption: function() {
if (!this.state.matchedAutocompleteOption) {
this.selectText()
} else {
this.selectOption(this.state.matchedAutocompleteOption, {focus: false});
}
},
selectOption: function(child, options) {
options = options || {};
this.setState({
// value: child.props.value,
// inputValue: getLabel(child),
matchedAutocompleteOption: null
}, function() {
this.props.onSelect(child.props.value, child);
this.hideList();
this.clearSelectedState(); // added
if (options.focus !== false)
this.selectInput();
}.bind(this));
this.refs.input.value = '' // added
},
selectText: function() {
var value = this.refs.input.value;
if(!value) return;
this.props.onSelect(value);
this.clearSelectedState();
this.refs.input.value = '' // added
},
focusNext: function(event) {
if(event.preventDefault) event.preventDefault();
if (this.state.menu.isEmpty) return;
var index = this.nextFocusableIndex(this.state.focusedIndex)
this.focusOptionAtIndex(index);
},
removeLastToken: function() {
if(this.props.onRemoveLast && !this.refs.input.value) {
this.props.onRemoveLast()
}
return true
},
focusPrevious: function(event) {
if(event.preventDefault) event.preventDefault();
if (this.state.menu.isEmpty) return;
var index = this.previousFocusableIndex(this.state.focusedIndex)
this.focusOptionAtIndex(index);
},
focusSelectedOption: function() {
var selectedIndex;
React.Children.forEach(this.props.children, function(child, index) {
if (child.props.value === this.state.value)
selectedIndex = index;
}.bind(this));
this.showList();
this.setState({
focusedIndex: selectedIndex
}, this.focusOption);
},
findInitialInputValue: function() {
// TODO: might not need this, we should know this in `makeMenu`
var inputValue;
React.Children.forEach(this.props.children, function(child) {
if (child.props.value === this.props.value)
inputValue = getLabel(child);
}.bind(this));
return inputValue;
},
clampIndex: function(index) {
if (index < 0) {
return this.props.children.length - 1
} else if (index >= this.props.children.length) {
return 0
}
return index
},
scanForFocusableIndex: function(index, increment) {
if (index === null || index === undefined) {
index = increment > 0 ? this.clampIndex(-1) : 0
}
var newIndex = index
while (true) {
newIndex = this.clampIndex(newIndex + increment)
if (newIndex === index ||
this.props.children[newIndex].props.isFocusable)
{
return newIndex
}
}
},
nextFocusableIndex: function(index) {
return this.scanForFocusableIndex(index, 1)
},
previousFocusableIndex: function(index) {
return this.scanForFocusableIndex(index, -1)
},
focusOptionAtIndex: function(index) {
if (!this.state.isOpen && this.state.value)
return this.focusSelectedOption();
this.showList();
var length = this.props.children.length;
if (index === -1)
index = length - 1;
else if (index === length)
index = 0;
this.setState({
focusedIndex: index
}, this.focusOption);
},
focusOption: function() {
var index = this.state.focusedIndex;
this.refs.list.childNodes[index].focus();
},
render: function() {
var ariaLabel = this.props['aria-label'] || 'Start typing to search. ' +
'Press the down arrow to navigate results. If you don\'t find an ' +
'acceptable option, you can input an alternative. Once you find or ' +
'input the tag you want, press Enter or Comma to add it.'
return div({className: this.getClassName()},
this.props.value,
this.state.inputValue,
input({
ref: 'input',
autoComplete: 'off',
spellCheck: 'false',
'aria-label': ariaLabel,
'aria-expanded': this.state.isOpen+'',
'aria-haspopup': 'true',
'aria-activedescendant': this.state.menu.activedescendant,
'aria-autocomplete': 'list',
'aria-owns': this.state.listId,
id: this.props.id,
disabled: this.props.isDisabled,
className: 'ic-tokeninput-input',
onFocus: this.handleInputFocus,
onClick: this.handleInputClick,
onChange: this.handleInputChange,
onBlur: this.handleInputBlur,
onKeyDown: this.handleKeydown,
onKeyUp: this.handleInputKeyUp,
placeholder: this.props.placeholder,
role: 'combobox'
}),
span({
'aria-hidden': 'true',
className: 'ic-tokeninput-button',
onClick: this.handleButtonClick
}, '▾'),
div({
id: this.state.listId,
ref: 'list',
className: 'ic-tokeninput-list',
role: 'listbox'
}, this.state.menu.children)
);
}
});
function getLabel(component) {
return component.props.label || component.props.children;
}
function matchFragment(userInput, firstChildLabel) {
userInput = userInput.toLowerCase();
firstChildLabel = firstChildLabel.toLowerCase();
if (userInput === '' || userInput === firstChildLabel)
return false;
if (firstChildLabel.toLowerCase().indexOf(userInput.toLowerCase()) === -1)
return false;
return true;
}