-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathSearchBox.jsx
541 lines (495 loc) · 17 KB
/
SearchBox.jsx
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
/**
* @component
*/
import classNames from 'clsx';
import PropTypes from 'prop-types';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import InputBox from '../../react-chayns-input_box/component/InputBox';
import ResultSelection from './result-selection/ResultSelection';
import './SearchBox.scss';
import { isNumber, isString } from '../../utils/is';
/**
* An autocomplete input to search through a list of entries.
*/
const SearchBox = ({
list,
disabled = false,
listValue = 'value',
listKey = 'key',
sortKey,
defaultValue,
onSelect,
value: valueProp,
stopPropagation = false,
showListWithoutInput = false,
inputValue: inputValueProp,
inputDefaultValue,
onChange,
className,
autoSelectFirst = false,
highlightInputInResult = true,
addInputToList = false,
hasOpenCloseIcon = false,
emptyKey,
onBlur,
...otherProps
}) => {
const getValue = useCallback(
(stringOrObjectOrNumber) => {
if (
isString(stringOrObjectOrNumber) ||
isNumber(stringOrObjectOrNumber) ||
!stringOrObjectOrNumber
) {
return stringOrObjectOrNumber;
}
return stringOrObjectOrNumber[listValue];
},
[listValue]
);
const getSortValue = useCallback(
(stringOrObjectOrNumber) => {
if (
isString(stringOrObjectOrNumber) ||
isNumber(stringOrObjectOrNumber) ||
!stringOrObjectOrNumber
) {
return stringOrObjectOrNumber;
}
return stringOrObjectOrNumber[sortKey ?? listValue];
},
[sortKey, listValue]
);
const getKey = useCallback(
(stringOrObjectOrNumber) => {
if (
isString(stringOrObjectOrNumber) ||
isNumber(stringOrObjectOrNumber)
) {
return stringOrObjectOrNumber;
}
if (!listKey || !stringOrObjectOrNumber) {
return null;
}
const key = stringOrObjectOrNumber[listKey];
if (!key && addInputToList) {
return stringOrObjectOrNumber[listValue];
}
return key;
},
[listKey, addInputToList, listValue]
);
const getItemByKey = useCallback(
(key) => {
let defaultReturnValue = {};
if (addInputToList) {
defaultReturnValue = { [listValue]: key };
}
if (list.length > 0) {
if (isString(list[0])) {
if (addInputToList) {
defaultReturnValue = key;
} else {
defaultReturnValue = '';
}
} else if (isNumber(list[0])) {
if (addInputToList) {
defaultReturnValue = Number(key);
} else {
defaultReturnValue = 0;
}
}
}
if (key === null || key === undefined) {
return defaultReturnValue;
}
const res = list.find(
(item) => String(getKey(item)) === String(key) || item === key
);
return res === undefined ? defaultReturnValue : res;
},
[addInputToList, list, listValue, getKey]
);
const isItemExisting = useCallback(
(value) => {
if (!value && value !== 0) {
return false;
}
return !!list.find(
(item) =>
String(getValue(item)) === String(value) ||
String(item) === String(value)
);
},
[getValue, list]
);
const [valueState, setValueState] = useState(defaultValue);
const value = valueProp !== null ? valueProp : valueState;
const [inputValueState, setInputValueState] = useState(
(inputDefaultValue !== null
? inputDefaultValue
: getValue(getItemByKey(value))) || ''
);
useEffect(() => {
setInputValueState(
(inputDefaultValue !== null
? inputDefaultValue
: getValue(getItemByKey(value))) || ''
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value, list]);
const inputValue =
inputValueProp !== null ? inputValueProp : inputValueState;
const [focusIndex, setFocusIndex] = useState(autoSelectFirst ? 0 : null);
const inputBoxRef = useRef(null);
const inputRef = useRef(null);
const [filteredList, setFilteredList] = useState([]);
const inputOnChange = useCallback(
(input) => {
if (onChange) onChange(input);
setInputValueState(input);
},
[setInputValueState, onChange]
);
const onItemClick = useCallback(
(e, item) => {
const selection = getKey(item) ?? e?.target.id;
setValueState(selection);
const itemValue = getValue(getItemByKey(selection));
let newInputValueState;
if (addInputToList && !itemValue) {
if (list.length >= 0 && isNumber(list[0])) {
newInputValueState = Number(selection);
} else {
newInputValueState = selection;
}
} else {
newInputValueState = itemValue;
}
setInputValueState(newInputValueState);
if (
onSelect &&
list &&
list.length > 0 &&
selection !== null &&
selection !== undefined
) {
onSelect(getItemByKey(selection));
}
if (stopPropagation) e?.stopPropagation();
if (inputBoxRef.current) inputBoxRef.current.blur();
if (inputRef.current) inputRef.current.ref?.blur();
},
[
getKey,
getValue,
getItemByKey,
addInputToList,
onSelect,
list,
stopPropagation,
]
);
const handleKeyDown = useCallback(
(ev) => {
if (!filteredList) return;
switch (ev.keyCode) {
case 40: // Arrow down
ev.preventDefault();
if (focusIndex === null) {
setFocusIndex(0);
} else if (focusIndex >= filteredList.length - 1) {
setFocusIndex(filteredList.length - 1);
} else {
setFocusIndex(focusIndex + 1);
}
break;
case 38: // Arrow up
ev.preventDefault();
if (focusIndex === null || focusIndex <= 0) {
setFocusIndex(0);
} else {
setFocusIndex(focusIndex - 1);
}
break;
case 13: // Enter
if (focusIndex !== null && filteredList[focusIndex]) {
onItemClick(ev, filteredList[focusIndex]);
inputRef.current.ref.blur();
setFocusIndex(null);
} else if (filteredList.length === 1) {
onItemClick(ev, filteredList[0]);
inputRef.current.ref.blur();
setFocusIndex(null);
}
break;
case 9: // Tabulator
if (filteredList.length === 1) {
onItemClick(ev, filteredList[0]);
inputRef.current.ref.blur();
setFocusIndex(null);
}
break;
case 27: // Escape
inputRef.current.ref.blur();
if (inputBoxRef.current) inputBoxRef.current.blur();
setFocusIndex(null);
break;
default:
break;
}
},
[filteredList, focusIndex, onItemClick]
);
useEffect(() => {
const inputValueString = Number.isNaN(inputValue)
? ''
: String(inputValue);
const returnList = list
?.filter(
(item) =>
String(getValue(item))
.toLowerCase()
.indexOf(inputValueString.toLowerCase()) >= 0 &&
(showListWithoutInput || inputValue)
)
.sort((a, b) => {
let aValue = getSortValue(a);
let bValue = getSortValue(b);
aValue = isString(aValue) ? aValue.toLowerCase() : aValue;
bValue = isString(bValue) ? bValue.toLowerCase() : bValue;
const aStartsWith = String(aValue).startsWith(
inputValueString.toLowerCase()
);
const bStartsWith = String(bValue).startsWith(
inputValueString.toLowerCase()
);
if (aStartsWith && !bStartsWith) return -1;
if (!aStartsWith && bStartsWith) return 1;
if (isString(aValue) || isString(bValue))
return aValue.localeCompare(bValue);
return aValue - bValue;
});
if (
addInputToList &&
!isItemExisting(inputValue) &&
list.length > 0 &&
inputValueString
) {
if (isString(list[0])) {
returnList.push(inputValue);
} else if (isNumber(list[0])) {
returnList.push(Number(inputValue));
} else {
returnList.push({ [listValue]: inputValue });
}
}
setFilteredList(returnList);
}, [
inputValue,
addInputToList,
list,
isItemExisting,
getValue,
getSortValue,
showListWithoutInput,
listValue,
]);
useEffect(() => {
let index = filteredList.findIndex(
(item) =>
(!(!inputValue && emptyKey) && value === getKey(item)) ||
(!inputValue && emptyKey === getKey(item))
);
if (index < 0) {
index = null;
}
setFocusIndex(index || (autoSelectFirst ? 0 : null));
}, [autoSelectFirst, emptyKey, filteredList, getKey, inputValue, value]);
useEffect(() => {
const item = filteredList[focusIndex];
const elem = document.getElementById(`${getKey(item)}`);
if (elem) {
if (typeof elem.scrollIntoViewIfNeeded === 'function') {
elem.scrollIntoViewIfNeeded(false);
} else if (typeof elem.scrollIntoView === 'function') {
elem.scrollIntoView({ behavior: 'smooth' });
}
}
}, [filteredList, focusIndex, getKey]);
return (
<InputBox
value={inputValue}
defaultValue={
!inputValue && inputDefaultValue ? inputDefaultValue : undefined
}
onChange={inputOnChange}
customProps={{ autoComplete: 'off' }}
type={list.length >= 0 && isNumber(list[0]) ? 'number' : 'text'}
onBlur={() => {
// return filtered list on onBlur event
if (typeof onBlur === 'function') {
onBlur(filteredList);
}
if (addInputToList) {
onItemClick(null, inputValue);
} else if (filteredList.length === 1) {
// select only matching item
onItemClick(null, filteredList[0]);
} else {
// select exact match (ignore case)
const item = list.find(
(i) =>
i[listValue]?.toLowerCase() ===
inputValue?.toLowerCase()
);
if (item) {
onItemClick(null, item);
} else {
inputRef.current?.ref?.blur();
}
}
}}
{...otherProps}
hasOpenCloseIcon={hasOpenCloseIcon}
ref={inputBoxRef}
disabled={disabled}
className={classNames(className, {
'cc__search-box--disabled': disabled,
})}
onKeyDown={handleKeyDown}
inputRef={(ref) => {
inputRef.current = ref;
}}
emptyValue={getValue(getItemByKey(emptyKey))}
>
{filteredList &&
filteredList.length > 0 &&
filteredList.map((item, index) => (
<div
key={getKey(item)}
id={getKey(item)}
className={classNames('cc__search-box__item ellipsis', {
'cc__search-box__item--selected':
(!(!inputValue && emptyKey) &&
value === getKey(item)) ||
index === focusIndex ||
(!inputValue && emptyKey === getKey(item)),
})}
onClick={onItemClick}
>
{highlightInputInResult && inputValue ? (
<ResultSelection
text={getValue(item)}
search={inputValue}
/>
) : (
getValue(item)
)}
</div>
))}
</InputBox>
);
};
SearchBox.propTypes = {
/**
* A callback that will be invoked when a value was selected.
*/
onSelect: PropTypes.func,
/**
* Disables any user interaction and renders the search box in a disabled
* style.
*/
disabled: PropTypes.bool,
/**
* An array of items to select from.
*/
list: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.object),
PropTypes.arrayOf(PropTypes.string),
PropTypes.arrayOf(PropTypes.number),
]),
/**
* The property name of a unique identifier in the `list` items.
*/
listKey: PropTypes.string,
/**
* The property name of the name of the `list` items that will be shown in
* the dropdown.
*/
listValue: PropTypes.string,
/**
* The property name to use for sorting the list. Default is listValue
*/
sortKey: PropTypes.string,
/**
* A classname string that will be set on the container component.
*/
className: PropTypes.string,
/**
* The default value of the search box as a key to one of the list items.
*/
defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Wether to stop propagation of click events to parent elements.
*/
stopPropagation: PropTypes.bool,
/**
* A DOM element into which the overlay will be rendered.
*/
parent: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
/**
* A React style object that will be applied to the outer-most container.
*/
style: PropTypes.objectOf(
PropTypes.oneOfType([PropTypes.string, PropTypes.number])
),
/**
* The current value of the search box as a key to one of the list items.
*/
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* The current value of the text input.
*/
inputValue: PropTypes.string,
/**
* Wether the list should be shown if there is no user input.
*/
showListWithoutInput: PropTypes.bool,
/**
* The default value of the input field. Has no effect when used with the
* `inputValue`-prop.
*/
inputDefaultValue: PropTypes.string,
/**
* The `onChange`-callback for the input element.
*/
onChange: PropTypes.func,
/**
* Wether the first list item should be automatically selected.
*/
autoSelectFirst: PropTypes.bool,
/**
* Whether the search term should be marked in the selection
*/
highlightInputInResult: PropTypes.bool,
/**
* Whether the input value should be added to the end of the result list.
* Allows also values which are not in the list.
*/
addInputToList: PropTypes.bool,
/**
* The key of the default value if nothing is selected or typed into the input.
*/
emptyKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Whether the input should have a small icon to open and close the result list.
*/
hasOpenCloseIcon: PropTypes.bool,
/**
* A callback that will be invoked when the user leaves the input.
*/
onBlur: PropTypes.func,
};
SearchBox.displayName = 'SearchBox';
export default SearchBox;