-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
ComboBox.js
433 lines (385 loc) · 12.3 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
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import cx from 'classnames';
import Downshift from 'downshift';
import PropTypes from 'prop-types';
import React from 'react';
import { settings } from 'carbon-components';
import { Checkmark16, WarningFilled16 } from '@carbon/icons-react';
import ListBox, { PropTypes as ListBoxPropTypes } from '../ListBox';
import { match, keys } from '../../internal/keyboard';
import setupGetInstanceId from '../../tools/setupGetInstanceId';
const { prefix } = settings;
const defaultItemToString = item => {
if (typeof item === 'string') {
return item;
}
return item && item.label;
};
const defaultShouldFilterItem = () => true;
const getInputValue = (props, state) => {
if (props.selectedItem) {
return props.itemToString(props.selectedItem);
}
// TODO: consistent `initialSelectedItem` behavior with other listbox components in v11
if (props.initialSelectedItem) {
return props.itemToString(props.initialSelectedItem);
}
return state.inputValue || '';
};
const findHighlightedIndex = ({ items, itemToString }, inputValue) => {
if (!inputValue) {
return -1;
}
const searchValue = inputValue.toLowerCase();
for (let i = 0; i < items.length; i++) {
const item = itemToString(items[i]).toLowerCase();
if (item.indexOf(searchValue) !== -1) {
return i;
}
}
return -1;
};
const getInstanceId = setupGetInstanceId();
export default class ComboBox extends React.Component {
static propTypes = {
/**
* 'aria-label' of the ListBox component.
*/
ariaLabel: PropTypes.string,
/**
* An optional className to add to the container node
*/
className: PropTypes.string,
/**
* Specify if the control should be disabled, or not
*/
disabled: PropTypes.bool,
/**
* Specify a custom `id` for the input
*/
id: PropTypes.string.isRequired,
/**
* Allow users to pass in an arbitrary item or a string (in case their items are an array of strings)
* from their collection that are pre-selected
*/
initialSelectedItem: PropTypes.oneOfType([
PropTypes.object,
PropTypes.string,
]),
/**
* We try to stay as generic as possible here to allow individuals to pass
* in a collection of whatever kind of data structure they prefer
*/
items: PropTypes.array.isRequired,
/**
* Helper function passed to downshift that allows the library to render a
* given item to a string label. By default, it extracts the `label` field
* from a given item to serve as the item label in the list
*/
itemToString: PropTypes.func,
/**
* Optional function to render items as custom components instead of strings.
* Defaults to null and is overriden by a getter
*/
itemToElement: PropTypes.func,
/**
* `onChange` is a utility for this controlled component to communicate to a
* consuming component when a specific dropdown item is selected.
* @param {{ selectedItem }}
*/
onChange: PropTypes.func.isRequired,
/**
* Used to provide a placeholder text node before a user enters any input.
* This is only present if the control has no items selected
*/
placeholder: PropTypes.string.isRequired,
/**
* Specify your own filtering logic by passing in a `shouldFilterItem`
* function that takes in the current input and an item and passes back
* whether or not the item should be filtered.
*/
shouldFilterItem: PropTypes.func,
/**
* Specify if the currently selected value is invalid.
*/
invalid: PropTypes.bool,
/**
* Message which is displayed if the value is invalid.
*/
invalidText: PropTypes.string,
/**
* For full control of the selection
*/
selectedItem: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
/**
* Specify a custom translation function that takes in a message identifier
* and returns the localized string for the message
*/
translateWithId: PropTypes.func,
/**
* Currently supports either the default type, or an inline variant
*/
type: ListBoxPropTypes.ListBoxType,
/**
* Specify the size of the ListBox. Currently supports either `sm`, `lg` or `xl` as an option.
*/
size: ListBoxPropTypes.ListBoxSize,
/**
* Callback function to notify consumer when the text input changes.
* This provides support to change available items based on the text.
* @param {string} inputText
*/
onInputChange: PropTypes.func,
/**
* should use "light theme" (white background)?
*/
light: PropTypes.bool,
/**
* Additional props passed to Downshift
*/
downshiftProps: PropTypes.shape(Downshift.propTypes),
};
static defaultProps = {
disabled: false,
itemToString: defaultItemToString,
itemToElement: null,
shouldFilterItem: defaultShouldFilterItem,
type: 'default',
ariaLabel: 'Choose an item',
light: false,
};
static getDerivedStateFromProps(nextProps, state) {
return { inputValue: getInputValue(nextProps, state) };
}
constructor(props) {
super(props);
this.textInput = React.createRef();
this.comboBoxInstanceId = getInstanceId();
this.state = {
inputValue: getInputValue(props, {}),
};
}
filterItems = (items, itemToString, inputValue) =>
items.filter(item =>
this.props.shouldFilterItem({
item,
itemToString,
inputValue,
})
);
handleOnChange = selectedItem => {
if (this.props.onChange) {
this.props.onChange({ selectedItem });
}
};
handleOnInputValueChange = inputValue => {
const { onInputChange } = this.props;
this.setState(
() => ({
// Default to empty string if we have a false-y `inputValue`
inputValue: inputValue || '',
}),
() => {
if (onInputChange) {
onInputChange(inputValue);
}
}
);
};
handleOnStateChange = (newState, { setHighlightedIndex }) => {
if (Object.prototype.hasOwnProperty.call(newState, 'inputValue')) {
const { inputValue } = newState;
setHighlightedIndex(findHighlightedIndex(this.props, inputValue));
}
};
onToggleClick = isOpen => event => {
if (event.target === this.textInput.current && isOpen) {
event.preventDownshiftDefault = true;
event.persist();
}
};
render() {
const {
className: containerClassName,
disabled,
id,
items,
itemToString,
itemToElement,
titleText,
helperText,
placeholder,
initialSelectedItem,
selectedItem,
ariaLabel,
translateWithId,
invalid,
invalidText,
light,
type, // eslint-disable-line no-unused-vars
size,
shouldFilterItem, // eslint-disable-line no-unused-vars
onChange, // eslint-disable-line no-unused-vars
onInputChange, // eslint-disable-line no-unused-vars
downshiftProps,
...rest
} = this.props;
const className = cx(`${prefix}--combo-box`, containerClassName);
const titleClasses = cx(`${prefix}--label`, {
[`${prefix}--label--disabled`]: disabled,
});
const comboBoxHelperId = !helperText
? undefined
: `combobox-helper-text-${this.comboBoxInstanceId}`;
const comboBoxLabelId = `combobox-label-${this.comboBoxInstanceId}`;
const title = titleText ? (
<label id={comboBoxLabelId} htmlFor={id} className={titleClasses}>
{titleText}
</label>
) : null;
const helperClasses = cx(`${prefix}--form__helper-text`, {
[`${prefix}--form__helper-text--disabled`]: disabled,
});
const helper = helperText ? (
<div id={comboBoxHelperId} className={helperClasses}>
{helperText}
</div>
) : null;
const wrapperClasses = cx(`${prefix}--list-box__wrapper`);
const comboBoxA11yId = `combobox-a11y-${this.comboBoxInstanceId}`;
const inputClasses = cx(`${prefix}--text-input`, {
[`${prefix}--text-input--empty`]: !this.state.inputValue,
});
// needs to be Capitalized for react to render it correctly
const ItemToElement = itemToElement;
const input = (
<Downshift
{...downshiftProps}
onChange={this.handleOnChange}
onInputValueChange={this.handleOnInputValueChange}
onStateChange={this.handleOnStateChange}
inputValue={this.state.inputValue || ''}
itemToString={itemToString}
defaultSelectedItem={initialSelectedItem}
selectedItem={selectedItem}>
{({
getButtonProps,
getInputProps,
getItemProps,
getRootProps,
isOpen,
inputValue,
selectedItem,
highlightedIndex,
clearSelection,
toggleMenu,
}) => (
<ListBox
className={className}
disabled={disabled}
invalid={invalid}
id={comboBoxA11yId}
aria-label={ariaLabel}
invalidText={invalidText}
isOpen={isOpen}
light={light}
size={size}
{...getRootProps({ refKey: 'innerRef' })}>
<ListBox.Field
id={id}
disabled={disabled}
aria-labelledby={comboBoxLabelId}
aria-describedby={comboBoxHelperId}
{...getButtonProps({
disabled,
onClick: this.onToggleClick(isOpen),
})}>
<input
className={inputClasses}
aria-labelledby={comboBoxA11yId}
tabIndex="0"
aria-disabled={disabled}
aria-controls={isOpen ? `${id}__menu` : null}
aria-owns={isOpen ? `${id}__menu` : null}
aria-autocomplete="list"
ref={this.textInput}
{...rest}
{...getInputProps({
disabled,
id,
placeholder,
onKeyDown: event => {
event.stopPropagation();
if (match(event, keys.Enter)) {
toggleMenu();
}
},
})}
/>
{invalid && (
<WarningFilled16
className={`${prefix}--list-box__invalid-icon`}
/>
)}
{inputValue && (
<ListBox.Selection
clearSelection={clearSelection}
translateWithId={translateWithId}
disabled={disabled}
/>
)}
<ListBox.MenuIcon
isOpen={isOpen}
translateWithId={translateWithId}
/>
</ListBox.Field>
{isOpen && (
<ListBox.Menu aria-label={ariaLabel} id={id}>
{this.filterItems(items, itemToString, inputValue).map(
(item, index) => {
const itemProps = getItemProps({ item, index });
return (
<ListBox.MenuItem
key={itemProps.id}
isActive={selectedItem === item}
isHighlighted={
highlightedIndex === index ||
(selectedItem && selectedItem.id === item.id) ||
false
}
title={itemToElement ? item.text : itemToString(item)}
{...itemProps}>
{itemToElement ? (
<ItemToElement key={itemProps.id} {...item} />
) : (
itemToString(item)
)}
{selectedItem === item && (
<Checkmark16
className={`${prefix}--list-box__menu-item__selected-icon`}
/>
)}
</ListBox.MenuItem>
);
}
)}
</ListBox.Menu>
)}
</ListBox>
)}
</Downshift>
);
return (
<div className={wrapperClasses}>
{title}
{helper}
{input}
</div>
);
}
}