1
0
Fork 0

feat: implement maxResultsPerGroup prop (#1891)

This commit is contained in:
Bojan Rajh 2023-05-17 22:18:50 +02:00 committed by GitHub
parent 2f21fd9b29
commit f82a73367a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 16 additions and 4 deletions

View file

@ -29,6 +29,7 @@ export interface DocSearchProps {
indexName: string;
placeholder?: string;
searchParameters?: SearchOptions;
maxResultsPerGroup?: number;
transformItems?: (items: DocSearchHit[]) => DocSearchHit[];
hitComponent?: (props: {
hit: InternalDocSearchHit | StoredDocSearchHit;

View file

@ -46,6 +46,7 @@ export function DocSearchModal({
indexName,
placeholder = 'Search docs',
searchParameters,
maxResultsPerGroup,
onClose = noop,
transformItems = identity,
hitComponent = Hit,
@ -240,7 +241,11 @@ export function DocSearchModal({
})
.then(({ results }) => {
const { hits, nbHits } = results[0];
const sources = groupBy(hits, (hit) => removeHighlightTags(hit));
const sources = groupBy(
hits,
(hit) => removeHighlightTags(hit),
maxResultsPerGroup
);
// We store the `lvl0`s to display them as search suggestions
// in the "no results" screen.
@ -271,7 +276,11 @@ export function DocSearchModal({
},
getItems() {
return Object.values(
groupBy(items, (item) => item.hierarchy.lvl1)
groupBy(
items,
(item) => item.hierarchy.lvl1,
maxResultsPerGroup
)
)
.map(transformItems)
.map((groupedHits) =>
@ -300,6 +309,7 @@ export function DocSearchModal({
[
indexName,
searchParameters,
maxResultsPerGroup,
searchClient,
onClose,
recentSearches,

View file

@ -1,6 +1,7 @@
export function groupBy<TValue extends Record<string, unknown>>(
values: TValue[],
predicate: (value: TValue) => string
predicate: (value: TValue) => string,
maxResultsPerGroup?: number
): Record<string, TValue[]> {
return values.reduce<Record<string, TValue[]>>((acc, item) => {
const key = predicate(item);
@ -11,7 +12,7 @@ export function groupBy<TValue extends Record<string, unknown>>(
// We limit each section to show 5 hits maximum.
// This acts as a frontend alternative to `distinct`.
if (acc[key].length < 5) {
if (acc[key].length < (maxResultsPerGroup || 5)) {
acc[key].push(item);
}