import React, { useCallback, useRef, useState } from 'react';
import cn from 'classnames';
import Flex from './Flex';
import { ErrorText } from './Typography';
import useOnClickOutside from 'indigo-react/lib/useOnClickOutside';
import AccessoryIcon from './AccessoryIcon';
// NOTE: if we really care about accessibility, we should pull in a dependency
export default function SelectInput({
// visuals
name,
label,
className,
accessory,
mono = false,
placeholder,
// callbacks
onValue,
onEnter,
// state from hook
focused,
pass,
visiblyPassed,
error,
data,
bind,
autoFocus,
disabled,
options,
// ignored
initialValue,
validators,
transformers,
// extra
...rest
}) {
const [isOpen, setIsOpen] = useState(false);
const ref = useRef();
// close select on outside clicks
useOnClickOutside(ref, useCallback(() => setIsOpen(false), [setIsOpen]));
const toggleOpen = useCallback(() => setIsOpen(isOpen => !isOpen), [
setIsOpen,
]);
const onChange = value => {
// TODO: provide setValue here?
// construct a pseudo event that sets the value correctly
bind.onChange({ target: { value } });
setIsOpen(false);
};
// redefine accessory because we still want to ignore it from the ..rest above
accessory = {isOpen ? '⬆' : '⬇'};
const text = options.find(o => o.value === data).text;
return (
{label}
{isOpen ? placeholder : text}
{accessory}
{isOpen && (
{options.map(option => (
{
e.stopPropagation();
onChange(option.value);
}}>
{option.text}
))}
)}
{error && (
{error}
)}
);
}