import React, { useEffect, useState } from 'react'; import styled from 'styled-components/macro'; import tw from 'twin.macro'; import Input from '@/components/elements/Input'; import Label from '@/components/elements/Label'; import { Location } from '@/api/admin/locations/getLocations'; import searchLocations from '@/api/admin/locations/searchLocations'; import InputSpinner from '@/components/elements/InputSpinner'; import { debounce } from 'debounce'; const Dropdown = styled.div<{ expanded: boolean }>` ${tw`absolute mt-1 w-full rounded-md bg-neutral-900 shadow-lg z-10`}; ${props => !props.expanded && tw`hidden`}; `; export default ({ defaultLocation }: { defaultLocation: Location }) => { const [ loading, setLoading ] = useState(false); const [ expanded, setExpanded ] = useState(false); const [ location, setLocation ] = useState(defaultLocation); const [ locations, setLocations ] = useState([]); const [ inputText, setInputText ] = useState(''); const onFocus = () => { setInputText(''); setLocations([]); setExpanded(true); }; const search = debounce((query: string) => { if (!expanded) { return; } if (query === '' || query.length < 2) { setLocations([]); return; } setLoading(true); searchLocations({ short: query }).then((locations) => { setLocations(locations); }).then(() => setLoading(false)); }, 250); const selectLocation = (location: Location) => { setLocation(location); }; useEffect(() => { setInputText(location.short); setExpanded(false); }, [ location ]); useEffect(() => { const handler = (e: KeyboardEvent) => { if (e.key !== 'Escape') { return; } setInputText(location.short); setExpanded(false); }; window.addEventListener('keydown', handler); return () => { window.removeEventListener('keydown', handler); }; }, [ expanded ]); return (
{ setInputText(e.currentTarget.value); search(e.currentTarget.value); }} />
{locations.length < 1 ? inputText.length < 2 ?

Please type 2 or more characters.

:

No results found.

:
    {locations.map(l => ( l.id === location.id ?
  • { e.stopPropagation(); selectLocation(l); }} >
    {l.short}
  • :
  • { e.stopPropagation(); selectLocation(l); }} >
    {l.short}
  • ))}
}
); };