import { ChangeEvent, FocusEvent, SyntheticEvent, useCallback } from 'react'; import { ariaDescribedByIds, enumOptionsIndexForValue, enumOptionsValueForIndex, 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, }: WidgetProps) { const { enumOptions, enumDisabled, emptyValue: optEmptyVal } = options; const emptyValue = multiple ? [] : ''; const handleFocus = useCallback( (event: FocusEvent) => { const newValue = getValue(event, multiple); return onFocus(id, enumOptionsValueForIndex(newValue, enumOptions, optEmptyVal)); }, [onFocus, id, schema, multiple, enumOptions, optEmptyVal] ); const handleBlur = useCallback( (event: FocusEvent) => { const newValue = getValue(event, multiple); return onBlur(id, enumOptionsValueForIndex(newValue, enumOptions, optEmptyVal)); }, [onBlur, id, schema, multiple, enumOptions, optEmptyVal] ); const handleChange = useCallback( (event: ChangeEvent) => { const newValue = getValue(event, multiple); return onChange(enumOptionsValueForIndex(newValue, enumOptions, optEmptyVal)); }, [onChange, schema, multiple, enumOptions, optEmptyVal] ); const selectedIndexes = enumOptionsIndexForValue(value, enumOptions, multiple); const showPlaceholderOption = !multiple && schema.default === undefined; return ( ); } export default SelectWidget;