forked from BuilderIO/builder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dropdown.tsx
78 lines (66 loc) · 2.32 KB
/
Dropdown.tsx
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
import TextField from '@material-ui/core/TextField';
import React, { useEffect } from 'react';
import Autocomplete from '@material-ui/lab/Autocomplete';
import { IOption } from '../models/IOption';
export const Dropdown = (inputProps: any) => {
const { onSelectChange, options, dimension, selectedValue, disableClear } = inputProps;
if (!options || !options.length) {
return <></>;
}
const currentlySelectedOption = getCurrentlySelectedOption(options, selectedValue);
const selectedOptionName = getOptionName(currentlySelectedOption);
const [inputValue, setInputValue] = React.useState(selectedOptionName);
useEffect(() => {
if (!selectedValue) {
setInputValue('');
}
}, [selectedValue]);
return (
<div data-testid="DROPDOWN" style={{ paddingTop: 10 }}>
<Autocomplete
data-testid={dimension}
fullWidth
disablePortal
disableClearable={!!disableClear}
value={selectedValue}
inputValue={inputValue}
onBlur={() => setInputValue(selectedOptionName)}
onInputChange={(event: any, newInputValue: string) => {
event && setInputValue(safeToString(newInputValue));
}}
onChange={(event: any, selectedOption: IOption | null) => {
if (!selectedOption) {
if (canClearValue(disableClear, event)) {
setInputValue('');
onSelectChange(null, dimension);
}
} else {
setInputValue(getOptionName(selectedOption));
onSelectChange(selectedOption.value, dimension);
}
}}
options={options}
getOptionLabel={(option: IOption) => getOptionName(option)}
renderInput={(params: any) => (
<TextField {...params} label={dimension} variant="outlined" />
)}
/>
</div>
);
};
function canClearValue(disableClear: any, event: any) {
return !disableClear && event?.type === 'click';
}
function safeToString(value: string): string {
return (value || '').toString();
}
function getOptionName(option: IOption | undefined | null) {
let optionName = '';
if (option) {
optionName = safeToString(option.name);
}
return optionName;
}
function getCurrentlySelectedOption(options: IOption[], selectedValue: any) {
return options.find((option: IOption) => option.value === selectedValue);
}