/** * External dependencies */ import { __ } from '@wordpress/i18n'; import { Icon, search } from '@wordpress/icons'; import { useContext, useEffect, useState } from '@wordpress/element'; import { navigateTo, getNewPath, useQuery } from '@woocommerce/navigation'; /** * Internal dependencies */ import './search.scss'; import { MARKETPLACE_PATH } from '../constants'; import { MarketplaceContext } from '../../contexts/marketplace-context'; const searchPlaceholder = __( 'Search for extensions, themes, and business services', 'woocommerce' ); const searchPlaceholderNoBusinessServices = __( 'Search for extensions and themes', 'woocommerce' ); /** * Search component. * * @return {JSX.Element} Search component. */ function Search(): JSX.Element { const [ searchTerm, setSearchTerm ] = useState( '' ); const { hasBusinessServices } = useContext( MarketplaceContext ); const query = useQuery(); const placeholder = hasBusinessServices ? searchPlaceholder : searchPlaceholderNoBusinessServices; useEffect( () => { if ( query.term ) { setSearchTerm( query.term ); } else { setSearchTerm( '' ); } }, [ query.term ] ); useEffect( () => { if ( query.tab !== 'search' ) { setSearchTerm( '' ); } }, [ query.tab ] ); const runSearch = () => { const term = searchTerm.trim(); const newQuery: { term?: string; tab?: string } = {}; if ( term !== '' ) { newQuery.term = term; newQuery.tab = 'search'; } // When the search term changes, we reset the query string on purpose. navigateTo( { url: getNewPath( newQuery, MARKETPLACE_PATH, {} ), } ); return []; }; const handleInputChange = ( event: React.ChangeEvent< HTMLInputElement > ) => { setSearchTerm( event.target.value ); }; const handleKeyUp = ( event: { key: string } ) => { if ( event.key === 'Enter' ) { runSearch(); } if ( event.key === 'Escape' ) { setSearchTerm( '' ); } }; return (
); } export default Search;