Skip to content

Commit f82a733

Browse files
authored
feat: implement maxResultsPerGroup prop (#1891)
1 parent 2f21fd9 commit f82a733

File tree

3 files changed

+16
-4
lines changed

3 files changed

+16
-4
lines changed

packages/docsearch-react/src/DocSearch.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export interface DocSearchProps {
2929
indexName: string;
3030
placeholder?: string;
3131
searchParameters?: SearchOptions;
32+
maxResultsPerGroup?: number;
3233
transformItems?: (items: DocSearchHit[]) => DocSearchHit[];
3334
hitComponent?: (props: {
3435
hit: InternalDocSearchHit | StoredDocSearchHit;

packages/docsearch-react/src/DocSearchModal.tsx

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ export function DocSearchModal({
4646
indexName,
4747
placeholder = 'Search docs',
4848
searchParameters,
49+
maxResultsPerGroup,
4950
onClose = noop,
5051
transformItems = identity,
5152
hitComponent = Hit,
@@ -240,7 +241,11 @@ export function DocSearchModal({
240241
})
241242
.then(({ results }) => {
242243
const { hits, nbHits } = results[0];
243-
const sources = groupBy(hits, (hit) => removeHighlightTags(hit));
244+
const sources = groupBy(
245+
hits,
246+
(hit) => removeHighlightTags(hit),
247+
maxResultsPerGroup
248+
);
244249

245250
// We store the `lvl0`s to display them as search suggestions
246251
// in the "no results" screen.
@@ -271,7 +276,11 @@ export function DocSearchModal({
271276
},
272277
getItems() {
273278
return Object.values(
274-
groupBy(items, (item) => item.hierarchy.lvl1)
279+
groupBy(
280+
items,
281+
(item) => item.hierarchy.lvl1,
282+
maxResultsPerGroup
283+
)
275284
)
276285
.map(transformItems)
277286
.map((groupedHits) =>
@@ -300,6 +309,7 @@ export function DocSearchModal({
300309
[
301310
indexName,
302311
searchParameters,
312+
maxResultsPerGroup,
303313
searchClient,
304314
onClose,
305315
recentSearches,

packages/docsearch-react/src/utils/groupBy.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
export function groupBy<TValue extends Record<string, unknown>>(
22
values: TValue[],
3-
predicate: (value: TValue) => string
3+
predicate: (value: TValue) => string,
4+
maxResultsPerGroup?: number
45
): Record<string, TValue[]> {
56
return values.reduce<Record<string, TValue[]>>((acc, item) => {
67
const key = predicate(item);
@@ -11,7 +12,7 @@ export function groupBy<TValue extends Record<string, unknown>>(
1112

1213
// We limit each section to show 5 hits maximum.
1314
// This acts as a frontend alternative to `distinct`.
14-
if (acc[key].length < 5) {
15+
if (acc[key].length < (maxResultsPerGroup || 5)) {
1516
acc[key].push(item);
1617
}
1718

0 commit comments

Comments
 (0)