Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement maxResultsPerGroup prop #1891

Merged
merged 1 commit into from May 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/docsearch-react/src/DocSearch.tsx
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
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
@@ -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