import React, { useEffect, useState } from 'react'; import color from '../../styles/colors'; import { Icon, iconTypes } from '../Icon'; import { Illustration } from '../Illustrations'; import SelectStyles from './Select.styles'; import type { SelectProps } from './types'; import InputStyles from '../Input/Input.styles'; const { DivWrapperStyled, LabelStyled: LabelStyledTrad } = InputStyles; const { DivStyledWrapper, DivStyledDescription, DropDownIcon, ErrorLabel, LabelStyled, NoDataTextStyled, Option, Options, PrefixIcon, PrefixSpan, SelectStyled, SelectedItem, } = SelectStyles; const Select: React.FC = ({ customNoDataText = 'No Data', defaultOptionIndex, description, disabled = false, errorMessage = '', id = String(Date.now()), ref, refTraditional, label, onChange, onChangeTraditional, onBlurTraditional, options = [], prefixIcon, prefixText, state = disabled ? 'disabled' : undefined, style, traditionalHTML5 = false, validation, value, width = '200px', ...props }: SelectProps) => { const [isOpen, setIsOpen] = useState(false); const [selectedOptionIndex, setSelectedOptionIndex] = useState(defaultOptionIndex); const toggling = (event: React.MouseEvent) => { if (disabled) return; setIsOpen(!isOpen); event.stopPropagation(); }; const onOptionClicked = (selectedIndex: number) => () => { setSelectedOptionIndex(selectedIndex); setIsOpen(false); if (onChange) { onChange(options[selectedIndex]); } }; useEffect(() => { const handleClickOutside = () => { setIsOpen(false); }; document.addEventListener('click', handleClickOutside); return () => { document.removeEventListener('click', handleClickOutside); }; }, []); useEffect(() => { if (value) { const valueOptionItem = options.find( (optionItem) => optionItem.id == value, ); setSelectedOptionIndex( valueOptionItem ? options.indexOf(valueOptionItem) : 0, ); } }, [selectedOptionIndex, value]); const renderFancySelectMode = () => ( {prefixIcon && ( )} {typeof selectedOptionIndex !== 'undefined' && ( <> {prefixText && {prefixText}} {options[selectedOptionIndex]?.prefix && !Boolean(prefixIcon) && ( {options[selectedOptionIndex]?.prefix} )} {options[selectedOptionIndex]?.label} )} {label && ( {label} )} {isOpen && ( {options?.length ? ( options.map( (option, index) => index !== selectedOptionIndex && ( ), ) ) : ( <> {customNoDataText} )} )} {state === 'error' && errorMessage ? ( {errorMessage} ) : ( description && ( {description} ) )} ); const renderTraditionalSelect = () => ( ) => onChangeTraditional && onChangeTraditional(event) } onBlur={(event: React.FocusEvent) => onBlurTraditional && onBlurTraditional(event) } required={validation?.required} {...props} > {options.map( (option, index) => index !== selectedOptionIndex && ( ), )} {label && ( {label} )} {description && ( {description} )} ); return traditionalHTML5 ? renderTraditionalSelect() : renderFancySelectMode(); }; export default Select;