import * as React from 'react'; import styled from 'styled-components'; import Downshift from 'downshift'; import mobileDetect from 'mobile-detect'; import { DropdownProps, Item, StyledDropdownArrowProps } from './interface'; import { Body } from '@Typography'; import * as tokens from '@tokens'; import { dim } from '@dim'; const DROPDOWN_WIDTH: string = '300px'; const DropdownWrapper = styled.div` position: relative; width: ${DROPDOWN_WIDTH}; & + & { margin-left: ${dim()}; } `; const PADDING_LR: number = 16; const LabelWrapper = styled.button` text-align: left; border: 1px solid ${tokens.colorBlack}; cursor: pointer; padding: 9px ${PADDING_LR}px 6px; vertical-align: sub; line-height: 1; user-select: none; width: 100%; span { font-style: italic; } `; const ItemsWrapper = styled.div` position: absolute; background-color: ${tokens.colorWhite}; border: 1px solid ${tokens.colorBlack}; border-top: none; z-index: 1; max-height: 300px; overflow: scroll; padding: ${dim(2)}; width: calc(100% - ${PADDING_LR * 2}px); ${Body} { &:hover { color: ${tokens.colorPink}; } } `; const DropdownArrow = styled.img` position: absolute; right: ${dim()}; top: 46%; transform: ${(props: StyledDropdownArrowProps) => (props.open ? 'rotate(180deg)' : 'rotate(0)')}; `; const LabelText = styled(Body)` margin: 0; `; const MobileSelect = styled.select` appearance: none; border: 1px solid ${tokens.colorBlack}; padding: ${dim(2)}; background-color: transparent; background-image: url('icons/dropdown-arrow.svg'); background-position: 94% 50%; background-repeat: no-repeat; border-radius: 0; font-size: 12px; width: ${DROPDOWN_WIDTH}; `; export const Dropdown: React.FC = ({ items = [], name = '', label = '', value = '', onChange = () => {}, onBlur = () => {} }) => { const md = new mobileDetect(navigator.userAgent); const isMovileDevice = !!md.phone() || !!md.tablet(); if (isMovileDevice) { return ( {items.map((item: Item) => ( ))} ); } const defaultSelectedItem = items.find((item: any) => item.value === value); return ( // @ts-ignore (i === null ? '' : i.label)} onChange={(input: Item) => onChange({ ...input })} onBlur={(input: Item) => onBlur({ ...input })} > {({ isOpen, selectedItem, toggleMenu, getRootProps, getItemProps }) => { const onClick = (e: React.MouseEvent) => toggleMenu(); return ( {label} {selectedItem && {selectedItem.label}} {isOpen && ( {items.map((item: Item) => ( {item.label} ))} )} ); }} ); };