-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
SelectWidget.tsx
97 lines (91 loc) · 2.34 KB
/
SelectWidget.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import React from "react";
import Form from "react-bootstrap/Form";
import {
FormContextType,
processSelectValue,
RJSFSchema,
StrictRJSFSchema,
WidgetProps,
} from "@rjsf/utils";
export default function SelectWidget<
T = any,
S extends StrictRJSFSchema = RJSFSchema,
F extends FormContextType = any
>({
schema,
id,
options,
required,
disabled,
readonly,
value,
multiple,
autofocus,
onChange,
onBlur,
onFocus,
placeholder,
rawErrors = [],
}: WidgetProps<T, S, F>) {
const { enumOptions, enumDisabled } = options;
const emptyValue = multiple ? [] : "";
function getValue(
event: React.FocusEvent | React.ChangeEvent | any,
multiple?: boolean
) {
if (multiple) {
return [].slice
.call(event.target.options as any)
.filter((o: any) => o.selected)
.map((o: any) => o.value);
} else {
return event.target.value;
}
}
return (
<Form.Control
as="select"
bsPrefix="custom-select"
id={id}
name={id}
value={typeof value === "undefined" ? emptyValue : value}
required={required}
multiple={multiple}
disabled={disabled || readonly}
autoFocus={autofocus}
className={rawErrors.length > 0 ? "is-invalid" : ""}
onBlur={
onBlur &&
((event: React.FocusEvent) => {
const newValue = getValue(event, multiple);
onBlur(id, processSelectValue<T, S, F>(schema, newValue, options));
})
}
onFocus={
onFocus &&
((event: React.FocusEvent) => {
const newValue = getValue(event, multiple);
onFocus(id, processSelectValue<T, S, F>(schema, newValue, options));
})
}
onChange={(event: React.ChangeEvent) => {
const newValue = getValue(event, multiple);
onChange(processSelectValue<T, S, F>(schema, newValue, options));
}}
>
{!multiple && schema.default === undefined && (
<option value="">{placeholder}</option>
)}
{(enumOptions as any).map(({ value, label }: any, i: number) => {
const disabled: any =
Array.isArray(enumDisabled) &&
(enumDisabled as any).indexOf(value) != -1;
return (
<option key={i} id={label} value={value} disabled={disabled}>
{label}
</option>
);
})}
</Form.Control>
);
}