import React, { ChangeEvent, FC, useCallback, useEffect, useRef } from 'react' import { useLocation } from '@reach/router' import { Box, InputProps, usePopoverState, PopoverDisclosure, PopoverInitialState, Popover, } from '@vtex/store-ui' import { useSearchBarContext } from './hooks' type Props = Omit & { popoverState?: PopoverInitialState } const SearchBarInput: FC = ({ variant, children, popoverState, ...forward }) => { const location = useLocation() const { syncTerm, setTerm, onSearch } = useSearchBarContext() const ref = useRef(null) // reference input const referenceRef = useRef(null) // reference container const { toggle: t, ...popover } = usePopoverState(popoverState) const { show, visible, hide } = popover // Close it whenever the page changes useEffect(() => { hide() // eslint-disable-next-line react-hooks/exhaustive-deps }, [location.pathname]) // When clicking in the input, always open but never close // search autocomplete const toggle = useCallback(() => { if (!visible) { show() } }, [show, visible]) useEffect(() => { // Focus input when input is clicked if (popover.visible) { ref.current?.focus() } // Blurs input when user clicks away else { ref.current?.blur() } }, [popover.visible]) return ( ) => { if (typeof e.target.value === 'string') { setTerm(e.target.value) } }} onKeyUp={(e: KeyboardEvent) => { if (e.key === 'Enter' && syncTerm) { onSearch(syncTerm) } }} aria-expanded={null} /> {visible ? children : null} ) } export default SearchBarInput