woocommerce/plugins/woocommerce-admin/client/marketplace/components/search/search.tsx

90 lines
2.0 KiB
TypeScript
Raw Normal View History

/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { Icon, search } from '@wordpress/icons';
2023-08-09 13:04:35 +00:00
import { useEffect, useState } from '@wordpress/element';
import { navigateTo, getNewPath, useQuery } from '@woocommerce/navigation';
/**
* Internal dependencies
*/
import './search.scss';
2023-08-16 09:56:15 +00:00
const searchPlaceholder = __( 'Search for extensions', 'woocommerce' );
/**
* Search component.
*
* @return {JSX.Element} Search component.
*/
2023-08-10 07:16:56 +00:00
function Search(): JSX.Element {
const [ searchTerm, setSearchTerm ] = useState( '' );
2023-08-09 13:04:35 +00:00
const query = useQuery();
2023-08-09 13:04:35 +00:00
useEffect( () => {
if ( query.term ) {
setSearchTerm( query.term );
}
2023-08-09 13:04:35 +00:00
}, [ query.term ] );
2023-08-09 13:04:35 +00:00
const runSearch = () => {
const term = searchTerm.trim();
// When the search term changes, we reset the category on purpose.
navigateTo( {
url: getNewPath( { term, category: null, tab: 'extensions' } ),
} );
2023-08-10 07:16:56 +00:00
return [];
};
const handleInputChange = (
event: React.ChangeEvent< HTMLInputElement >
) => {
setSearchTerm( event.target.value );
};
const handleKeyUp = ( event: { key: string } ) => {
if ( event.key === 'Enter' ) {
runSearch();
}
2023-08-09 13:04:35 +00:00
if ( event.key === 'Escape' ) {
setSearchTerm( '' );
}
};
return (
<div className="woocommerce-marketplace__search">
<label
className="screen-reader-text"
htmlFor="woocommerce-marketplace-search-query"
>
{ searchPlaceholder }
</label>
<input
id="woocommerce-marketplace-search-query"
value={ searchTerm }
className="woocommerce-marketplace__search-input"
type="search"
name="woocommerce-marketplace-search-query"
placeholder={ searchPlaceholder }
onChange={ handleInputChange }
onKeyUp={ handleKeyUp }
/>
<button
id="woocommerce-marketplace-search-button"
className="woocommerce-marketplace__search-button"
aria-label={ __( 'Search', 'woocommerce' ) }
onClick={ runSearch }
>
<Icon icon={ search } size={ 32 } />
</button>
</div>
);
}
export default Search;