Skip to content

Commit

Permalink
feat: implement maxResultsPerGroup prop
Browse files Browse the repository at this point in the history
  • Loading branch information
bojanrajh committed May 17, 2023
1 parent 2f21fd9 commit 7f03b62
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
6 changes: 4 additions & 2 deletions packages/docsearch-react/src/DocSearchModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export function DocSearchModal({
indexName,
placeholder = 'Search docs',
searchParameters,
maxResultsPerGroup,
onClose = noop,
transformItems = identity,
hitComponent = Hit,
Expand Down Expand Up @@ -240,7 +241,7 @@ 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.
Expand Down Expand Up @@ -271,7 +272,7 @@ export function DocSearchModal({
},
getItems() {
return Object.values(
groupBy(items, (item) => item.hierarchy.lvl1)
groupBy(items, (item) => item.hierarchy.lvl1, maxResultsPerGroup)
)
.map(transformItems)
.map((groupedHits) =>
Expand Down Expand Up @@ -300,6 +301,7 @@ export function DocSearchModal({
[
indexName,
searchParameters,
maxResultsPerGroup,
searchClient,
onClose,
recentSearches,
Expand Down
5 changes: 3 additions & 2 deletions packages/docsearch-react/src/utils/groupBy.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand All @@ -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);
}

Expand Down

0 comments on commit 7f03b62

Please sign in to comment.