import { Box , Center , FormControl , Input , Text } from '@chakra-ui/react' ; import { useRef , useState } from 'react' ; import { useNavigate } from 'react-router-dom' ; import { trim } from '../../uitls/trim' ; export function SearchBar ( ) { const navigate = useNavigate ( ) ; const [ isInputVisible , setIsInputVisible ] = useState ( false ) ; const [ input , setInput ] = useState ( '' ) ; const inputRef = useRef < HTMLInputElement | null > ( null ) ; function showInput ( ) { setIsInputVisible ( true ) ; requestAnimationFrame ( ( ) => { inputRef . current ?. focus ( ) ; } ) ; } function hideInput ( ) { setIsInputVisible ( false ) ; } function handleEnter ( event ) { const isEnter = event . key === 'Enter' ; const isEsc = event . key === 'Escape' ; const sanatizedInput = trim ( input ) ; if ( ( ! isEnter && ! isEsc ) || ! sanatizedInput ) { return ; } setIsInputVisible ( false ) ; if ( isEsc ) { setInput ( '' ) ; if ( inputRef . current ) { inputRef . current . value = '' ; } } if ( isEnter ) { if ( sanatizedInput !== input ) { setInput ( sanatizedInput ) ; if ( inputRef . current ) { inputRef . current . value = sanatizedInput ; } } navigate ( `/search/${ sanatizedInput }` ) ; } } return ( < Box position = "relative" w = "350px" sx = { { WebkitAppRegion : 'no-drag' } } > < Center userSelect = "none" display = { isInputVisible ? 'none' : 'flex' } onClick = { showInput } rounded = "5px" color = "whiteAlpha.600" bgColor = "whiteAlpha.300" transition = "all 200ms ease" _hover = { { bgColor : 'whiteAlpha.400' , color : 'whiteAlpha.800' } } w = "100%" h = "25px" > < Text > { input ? input : 'Search questions and answers' } < /Text> < /Center> < FormControl display = { isInputVisible ? 'block' : 'none' } > < Input ref = { inputRef } onChange = { ( event ) => setInput ( event . target . value ) } onBlur = { hideInput } onKeyDown = { handleEnter } bgColor = "white" rounded = "5px" size = "xs" h = "25px" / > < /FormControl> { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } < /Box>); }