Skip to content

Commit

Permalink
Put results that contains the title on top of the list
Browse files Browse the repository at this point in the history
  • Loading branch information
david-szabo97 committed Jan 28, 2021
1 parent be3619d commit 20937fc
Showing 1 changed file with 19 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* External dependencies
*/
import { map } from 'lodash';
import { map, sortBy, keyBy } from 'lodash';

/**
* WordPress dependencies
Expand Down Expand Up @@ -61,16 +61,17 @@ export default function SearchResults( { items, search } ) {
},
[ items, itemType ]
);
const itemInfosMap = useMemo( () => keyBy( itemInfos, 'slug' ), [
itemInfos,
] );

const itemsFiltered = useMemo( () => {
if ( items === null || search.length === 0 ) {
return [];
}

return items.filter( ( { slug } ) => {
const { title, description } = itemInfos.find(
( info ) => info.slug === slug
);
const { title, description } = itemInfosMap[ slug ];

return (
normalizedSearch( slug, search ) ||
Expand All @@ -80,14 +81,27 @@ export default function SearchResults( { items, search } ) {
} );
}, [ items, itemInfos, search ] );

const itemsSorted = useMemo( () => {
if ( ! itemsFiltered ) {
return [];
}

return sortBy( itemsFiltered, [
( { slug } ) => {
const { title } = itemInfosMap[ slug ];
return ! normalizedSearch( title, search );
},
] );
}, [ itemsFiltered, search ] );

const ItemComponent =
itemType === 'wp_template' || itemType === 'wp_template_part'
? TemplateNavigationItem
: ContentNavigationItem;

return (
<NavigationGroup title={ __( 'Search results' ) }>
{ map( itemsFiltered, ( item ) => (
{ map( itemsSorted, ( item ) => (
<ItemComponent
item={ item }
key={ `${ item.taxonomy || item.type }-${ item.id }` }
Expand Down

0 comments on commit 20937fc

Please sign in to comment.