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 4470920
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
1 change: 1 addition & 0 deletions packages/docsearch-react/src/DocSearch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export interface DocSearchProps {
indexName: string;
placeholder?: string;
searchParameters?: SearchOptions;
maxResultsPerGroup?: number;
transformItems?: (items: DocSearchHit[]) => DocSearchHit[];
hitComponent?: (props: {
hit: InternalDocSearchHit | StoredDocSearchHit;
Expand Down
14 changes: 12 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,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.
Expand Down Expand Up @@ -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) =>
Expand Down Expand Up @@ -300,6 +309,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 4470920

Please sign in to comment.