-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelect.tsx
More file actions
93 lines (85 loc) · 2.42 KB
/
Select.tsx
File metadata and controls
93 lines (85 loc) · 2.42 KB
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
import MuiFormControl from "@mui/material/FormControl";
import MuiInputLabel from "@mui/material/InputLabel";
import MuiMenuItem from "@mui/material/MenuItem";
import MuiSelect, { type SelectChangeEvent } from "@mui/material/Select";
import type { ComponentState, ComponentProps } from "@/index";
import { isString } from "@/utils/isString";
import { Tooltip } from "./Tooltip";
export type SelectOption =
| string
| number
| [string, string]
| [number, string]
| { value: string | number; label?: string };
interface SelectState extends ComponentState {
options?: SelectOption[];
multiple?: boolean;
}
interface SelectProps extends ComponentProps, SelectState {}
export function Select({
type,
id,
name,
value,
options,
disabled,
style,
tooltip,
label,
multiple = false,
onChange,
}: SelectProps) {
const handleChange = (event: SelectChangeEvent<unknown>) => {
if (id) {
let newValue: string | number | (string | number)[] = multiple
? (event.target.value as (string | number)[])
: (event.target.value as string | number);
if (!multiple && typeof value === "number") {
newValue = Number.parseInt(newValue as string);
}
onChange({
componentType: type,
id: id,
property: "value",
value: newValue,
});
}
};
return (
<Tooltip title={tooltip}>
<MuiFormControl variant="filled" size="small" style={style}>
{label && <MuiInputLabel id={`${id}-label`}>{label}</MuiInputLabel>}
<MuiSelect
labelId={`${id}-label`}
id={id}
name={name}
value={value}
disabled={disabled}
multiple={multiple}
onChange={handleChange}>
{Array.isArray(options) &&
options
.map(normalizeSelectOption)
.map(([optionValue, optionLabel], index) => (
<MuiMenuItem key={index} value={optionValue}>
{optionLabel}
</MuiMenuItem>
))}
</MuiSelect>
</MuiFormControl>
</Tooltip>
);
}
function normalizeSelectOption(
option: SelectOption
): [string | number, string] {
if (isString(option)) {
return [option, option];
} else if (typeof option === "number") {
return [option, option.toString()];
} else if (Array.isArray(option)) {
return option;
} else {
return [option.value, option.label || `${option.value}`];
}
}