| 1 |
import { FocusEvent } from 'react'; |
| 2 |
import FormControlLabel from '@mui/material/FormControlLabel'; |
| 3 |
import FormLabel from '@mui/material/FormLabel'; |
| 4 |
import Radio from '@mui/material/Radio'; |
| 5 |
import RadioGroup from '@mui/material/RadioGroup'; |
| 6 |
import { |
| 7 |
ariaDescribedByIds, |
| 8 |
enumOptionsIndexForValue, |
| 9 |
enumOptionsValueForIndex, |
| 10 |
labelValue, |
| 11 |
optionId, |
| 12 |
FormContextType, |
| 13 |
RJSFSchema, |
| 14 |
StrictRJSFSchema, |
| 15 |
WidgetProps, |
| 16 |
} from '@rjsf/utils'; |
| 17 |
|
| 18 |
/** The `RadioWidget` is a widget for rendering a radio group. |
| 19 |
* It is typically used with a string property constrained with enum options. |
| 20 |
* |
| 21 |
* @param props - The `WidgetProps` for this component |
| 22 |
*/ |
| 23 |
export default function RadioWidget<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>({ |
| 24 |
id, |
| 25 |
options, |
| 26 |
value, |
| 27 |
required, |
| 28 |
disabled, |
| 29 |
readonly, |
| 30 |
label, |
| 31 |
hideLabel, |
| 32 |
onChange, |
| 33 |
onBlur, |
| 34 |
onFocus, |
| 35 |
}: WidgetProps<T, S, F>) { |
| 36 |
const { enumOptions, enumDisabled, emptyValue } = options; |
| 37 |
|
| 38 |
const _onChange = (_: any, value: any) => onChange(enumOptionsValueForIndex<S>(value, enumOptions, emptyValue)); |
| 39 |
const _onBlur = ({ target: { value } }: FocusEvent<HTMLInputElement>) => |
| 40 |
onBlur(id, enumOptionsValueForIndex<S>(value, enumOptions, emptyValue)); |
| 41 |
const _onFocus = ({ target: { value } }: FocusEvent<HTMLInputElement>) => |
| 42 |
onFocus(id, enumOptionsValueForIndex<S>(value, enumOptions, emptyValue)); |
| 43 |
|
| 44 |
const row = options ? options.inline : false; |
| 45 |
const selectedIndex = enumOptionsIndexForValue<S>(value, enumOptions) ?? null; |
| 46 |
|
| 47 |
return ( |
| 48 |
<> |
| 49 |
{labelValue( |
| 50 |
<FormLabel required={required} htmlFor={id}> |
| 51 |
{label || undefined} |
| 52 |
</FormLabel>, |
| 53 |
hideLabel |
| 54 |
)} |
| 55 |
<RadioGroup |
| 56 |
id={id} |
| 57 |
name={id} |
| 58 |
value={selectedIndex} |
| 59 |
row={row as boolean} |
| 60 |
onChange={_onChange} |
| 61 |
onBlur={_onBlur} |
| 62 |
onFocus={_onFocus} |
| 63 |
aria-describedby={ariaDescribedByIds<T>(id)} |
| 64 |
> |
| 65 |
{Array.isArray(enumOptions) && |
| 66 |
enumOptions.map((option, index) => { |
| 67 |
const itemDisabled = Array.isArray(enumDisabled) && enumDisabled.indexOf(option.value) !== -1; |
| 68 |
const radio = ( |
| 69 |
<FormControlLabel |
| 70 |
control={<Radio name={id} id={optionId(id, index)} color='primary' />} |
| 71 |
label={option.label} |
| 72 |
value={String(index)} |
| 73 |
key={index} |
| 74 |
disabled={disabled || itemDisabled || readonly} |
| 75 |
/> |
| 76 |
); |
| 77 |
|
| 78 |
return radio; |
| 79 |
})} |
| 80 |
</RadioGroup> |
| 81 |
</> |
| 82 |
); |
| 83 |
} |