import * as React from "react"; import styled from "styled-components"; import { KeyboardArrowDown, KeyboardArrowUp } from "@rimble/icons"; import { Box, Flex, Text } from "rimble-ui"; import { baseColors, colors, fonts } from "../../../themes"; export const Option = styled(Box)` &:hover { background-color: ${colors.primary.background}; } &:hover span { color: ${colors.primary.base}; } `; interface DropDownOption { name: string; value: string; } export interface DropDownProps { options: DropDownOption[]; arrowColor?: string; combinedSearch?: boolean; defaultSelectedValue?: string; optionsTextProps?: { [key: string]: any }; disabled?: boolean; style?: { [key: string]: any }; onChange(value: string, index: number): void; } export const DropDown: React.FunctionComponent = (props) => { const { combinedSearch } = props; const node = React.useRef() as React.MutableRefObject; const [selectedOption, setSelectedOption] = React.useState( props.defaultSelectedValue ? props.options.filter((option) => option.value === props.defaultSelectedValue)[0] || props.options[0] : props.options[0], ); const [isOpen, setIsOpen] = React.useState(false); const toggle = () => !props.disabled && setIsOpen(!isOpen); const onOptionClicked = (option: DropDownOption) => () => { setSelectedOption(option); setIsOpen(false); props.onChange(option.value, props.options.indexOf(option)); }; const onClickOutside = (e: any) => { if (node.current.contains(e.target)) { return; } setIsOpen(false); }; React.useEffect(() => { document.addEventListener("mousedown", onClickOutside); return () => { document.removeEventListener("mousedown", onClickOutside); }; }); const optionsTextProps = { color: colors.silver, fontSize: 2, fontFamily: fonts.sansSerif, ...props.optionsTextProps, }; const selectedOptionTextProps = { ...optionsTextProps, style: { color: baseColors.black, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", ...props.optionsTextProps?.style, }, }; return ( {selectedOption.name} {isOpen ? ( ) : ( )} {isOpen && ( {props.options.map((option: any, key: number) => { if (option !== selectedOption) { return ( ); } return null; })} {props.children} )} ); };