| 1 |
/** |
| 2 |
* WordPress dependencies. |
| 3 |
*/ |
| 4 |
import { useMemo, WPElement } from '@wordpress/element'; |
| 5 |
import { __ } from '@wordpress/i18n'; |
| 6 |
|
| 7 |
/** |
| 8 |
* Internal dependencies. |
| 9 |
*/ |
| 10 |
import { useApiSearch } from '../../../api-search'; |
| 11 |
import { sortOptions } from '../../config'; |
| 12 |
|
| 13 |
/** |
| 14 |
* Search results component. |
| 15 |
* |
| 16 |
* @returns {WPElement} Component element. |
| 17 |
*/ |
| 18 |
export default () => { |
| 19 |
const { |
| 20 |
args: { orderby, order }, |
| 21 |
search, |
| 22 |
} = useApiSearch(); |
| 23 |
|
| 24 |
/** |
| 25 |
* The key for the current sorting option. |
| 26 |
*/ |
| 27 |
const currentOption = useMemo(() => { |
| 28 |
return Object.keys(sortOptions).find((key) => { |
| 29 |
return sortOptions[key].orderby === orderby && sortOptions[key].order === order; |
| 30 |
}); |
| 31 |
}, [orderby, order]); |
| 32 |
|
| 33 |
/** |
| 34 |
* Handle sorting option change. |
| 35 |
* |
| 36 |
* @param {Event} event Change event. |
| 37 |
*/ |
| 38 |
const onChange = (event) => { |
| 39 |
const { orderby, order } = sortOptions[event.target.value]; |
| 40 |
|
| 41 |
search({ orderby, order }); |
| 42 |
}; |
| 43 |
|
| 44 |
return ( |
| 45 |
<label className="ep-search-sort" htmlFor="ep-sort"> |
| 46 |
<span className="ep-search-sort__label">{__('Sort by', 'elasticpress')}</span>{' '} |
| 47 |
<select |
| 48 |
className="ep-search-sort__options" |
| 49 |
id="ep-sort" |
| 50 |
onChange={onChange} |
| 51 |
value={currentOption} |
| 52 |
> |
| 53 |
{Object.entries(sortOptions).map(([key, { name }]) => ( |
| 54 |
<option key={key} value={key}> |
| 55 |
{name} |
| 56 |
</option> |
| 57 |
))} |
| 58 |
</select> |
| 59 |
</label> |
| 60 |
); |
| 61 |
}; |
| 62 |
|