import { ChangeEvent, FocusEvent, SyntheticEvent, useCallback } from 'react'; import { ariaDescribedByIds, enumOptionSelectedValue, enumOptionValueDecoder, enumOptionValueEncoder, getOptionValueFormat, FormContextType, RJSFSchema, StrictRJSFSchema, WidgetProps, } from '@rjsf/utils'; function getValue(event: SyntheticEvent, multiple: boolean) { if (multiple) { return Array.from((event.target as HTMLSelectElement).options) .slice() .filter((o) => o.selected) .map((o) => o.value); } return (event.target as HTMLSelectElement).value; } /** The `SelectWidget` is a widget for rendering dropdowns. * It is typically used with string properties constrained with enum options. * * @param props - The `WidgetProps` for this component */ function SelectWidget({ schema, id, options, value, required, disabled, readonly, multiple = false, autofocus = false, onChange, onBlur, onFocus, placeholder, htmlName, }: WidgetProps) { const { enumOptions, enumDisabled, emptyValue: optEmptyVal } = options; const emptyValue = multiple ? [] : ''; const optionValueFormat = getOptionValueFormat(options); const handleFocus = useCallback( (event: FocusEvent) => { const newValue = getValue(event, multiple); return onFocus(id, enumOptionValueDecoder(newValue, enumOptions, optionValueFormat, optEmptyVal)); }, [onFocus, id, multiple, enumOptions, optEmptyVal, optionValueFormat], ); const handleBlur = useCallback( (event: FocusEvent) => { const newValue = getValue(event, multiple); return onBlur(id, enumOptionValueDecoder(newValue, enumOptions, optionValueFormat, optEmptyVal)); }, [onBlur, id, multiple, enumOptions, optEmptyVal, optionValueFormat], ); const handleChange = useCallback( (event: ChangeEvent) => { const newValue = getValue(event, multiple); return onChange(enumOptionValueDecoder(newValue, enumOptions, optionValueFormat, optEmptyVal)); }, [onChange, multiple, enumOptions, optEmptyVal, optionValueFormat], ); const selectValue = enumOptionSelectedValue(value, enumOptions, multiple, optionValueFormat, emptyValue); const showPlaceholderOption = !multiple && schema.default === undefined; return ( ); } export default SelectWidget;