import { useEffect, useState, useRef } from 'react'; import { EDIT_ACCESS_RUSSIAN, ROLES_ID_RUSSIAN_NAME } from '../../../constants/constants'; import { SelectWrapper, SelectContainer, SelectButton, Dropdown, Option, OptionName, Chevron, SelectedValue, Placeholder, } from './StyledComponents'; export const SelectRoles = ({ onChange, initialValue, excludeAdmin = true, }) => { const [options, setOptions] = useState([]); useEffect(() => { const options = Object.entries(ROLES_ID_RUSSIAN_NAME) .map(([id, name]) => ({ id: parseInt(id), name, })) .filter((option) => !excludeAdmin || option.id !== 1); setOptions(options); }, []); return ( ); }; const Select = ({ options, onChange, initialValue, valueKey = 'id', labelKey = 'name', }) => { const [isOpen, setIsOpen] = useState(false); const [selectedOption, setSelectedOption] = useState(null); const selectRef = useRef(null); useEffect(() => { const handleClickOutside = (event) => { if ( isOpen && selectRef.current && !selectRef.current.contains(event.target) ) { setIsOpen(false); } }; const handleEscapeKey = (event) => { if ( isOpen && event.key === 'Escape' && selectRef.current && !selectRef.current.contains(event.target) ) { setIsOpen(false); } }; document.addEventListener('mousedown', handleClickOutside); document.addEventListener('keydown', handleEscapeKey); return () => { document.removeEventListener('mousedown', handleClickOutside); document.removeEventListener('keydown', handleEscapeKey); }; }, [isOpen]); useEffect(() => { if (initialValue !== undefined) { const option = options.find((opt) => opt[valueKey] === initialValue); setSelectedOption(option); } else { setSelectedOption(null); } }, [initialValue, options, valueKey]); const handleOptionClick = (option) => { setSelectedOption(option); setIsOpen(false); onChange?.(option[valueKey]); }; if (!options.length) return null; return ( setIsOpen(!isOpen)} type="button"> {selectedOption ? ( {selectedOption[labelKey]} ) : ( Выберите... )} {isOpen && ( {options.map((option, index) => ( ))} )} ); };