Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type AutocompleteIndexProps<
T = { objectID: string; __indexName: string } & Record<string, unknown>
> = {
items: T[];
HeaderComponent?: (props: { items: T[] }) => JSX.Element;
ItemComponent: (props: { item: T; onSelect: () => void }) => JSX.Element;
getItemProps: (
item: T,
Expand All @@ -25,6 +26,10 @@ export type AutocompleteIndexClassNames = {
* Class names to apply to the list element
*/
list: string | string[];
/**
* Class names to apply to the header element
*/
header: string | string[];
/**
* Class names to apply to each item element
*/
Expand All @@ -33,10 +38,21 @@ export type AutocompleteIndexClassNames = {

export function createAutocompleteIndexComponent({ createElement }: Renderer) {
return function AutocompleteIndex(userProps: AutocompleteIndexProps) {
const { items, ItemComponent, getItemProps, classNames = {} } = userProps;
const {
items,
HeaderComponent,
ItemComponent,
getItemProps,
classNames = {},
} = userProps;

return (
<div className={cx('ais-AutocompleteIndex', classNames.root)}>
{HeaderComponent && (
<div className={cx('ais-AutocompleteIndexHeader', classNames.header)}>
<HeaderComponent items={items} />
</div>
)}
<ol className={cx('ais-AutocompleteIndexList', classNames.list)}>
{items.map((item, index) => {
const { className, onSelect, ...itemProps } = getItemProps(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,22 @@ function AutocompleteWrapper<TItem extends BaseHit>({
templates: indicesConfig[i].templates,
});
}
const headerComponent = indicesConfig[i].templates?.header
? ({
items,
}: Parameters<
NonNullable<AutocompleteIndexProps['HeaderComponent']>
>[0]) => {
return (
<TemplateComponent
{...renderState.indexTemplateProps[i]}
templateKey="header"
rootTagName="fragment"
data={{ items }}
/>
);
}
: undefined;
const itemComponent = ({
item,
onSelect,
Expand All @@ -217,6 +233,7 @@ function AutocompleteWrapper<TItem extends BaseHit>({
return (
<AutocompleteIndex
key={indexId}
HeaderComponent={headerComponent}
ItemComponent={itemComponent}
items={hits.map((item) => ({ ...item, __indexName: indexId }))}
getItemProps={getItemProps}
Expand All @@ -237,6 +254,10 @@ export type AutocompleteTemplates<TItem extends BaseHit> = Partial<

type IndexConfig<TItem extends BaseHit> = AutocompleteIndexConfig<TItem> & {
templates?: Partial<{
/**
* Template to use for the header, before the list of items.
*/
header: Template<{ items: TItem[] }>;
/**
* Template to use for each result. This template will receive an object containing a single record.
*/
Expand Down Expand Up @@ -308,22 +329,28 @@ export function EXPERIMENTAL_autocomplete<TItem extends BaseHit = BaseHit>(

const indicesConfig = [...indices];
if (showSuggestions?.indexName) {
const suggestionsSuit = component('AutocompleteSuggestions');
indicesConfig.unshift({
indexName: showSuggestions.indexName,
templates: {
// Temporarily force casting until the coming refactoring
item: (showSuggestions.templates?.item ||
AutocompleteSuggestion) as unknown as Template<{ item: TItem }>,
// @ts-expect-error
item: AutocompleteSuggestion,
...showSuggestions.templates,
},
cssClasses: {
root: cx(suggestionsSuit(), showSuggestions.cssClasses?.root),
root: cx(
'ais-AutocompleteSuggestions',
showSuggestions.cssClasses?.root
),
list: cx(
suggestionsSuit({ descendantName: 'list' }),
'ais-AutocompleteSuggestionsList',
showSuggestions.cssClasses?.list
),
header: cx(
'ais-AutocompleteSuggestionsHeader',
showSuggestions.cssClasses?.header
),
item: cx(
suggestionsSuit({ descendantName: 'item' }),
'ais-AutocompleteSuggestionsItem',
showSuggestions.cssClasses?.item
),
},
Expand Down
24 changes: 14 additions & 10 deletions packages/react-instantsearch/src/widgets/Autocomplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ import type {
AutocompleteIndexConfig,
Pragma,
AutocompleteClassNames,
AutocompleteIndexProps,
} from 'instantsearch-ui-components';
import type { BaseHit, Hit } from 'instantsearch.js';
import type { BaseHit } from 'instantsearch.js';
import type { ComponentProps } from 'react';

const Autocomplete = createAutocompleteComponent({
Expand Down Expand Up @@ -56,13 +57,9 @@ const usePropGetters = createAutocompletePropGetters({
useState,
});

type ItemComponentProps<TItem extends BaseHit> = React.ComponentType<{
item: Hit<TItem>;
onSelect: () => void;
}>;

type IndexConfig<TItem extends BaseHit> = AutocompleteIndexConfig<TItem> & {
itemComponent: ItemComponentProps<TItem>;
headerComponent?: AutocompleteIndexProps<TItem>['HeaderComponent'];
itemComponent: AutocompleteIndexProps<TItem>['ItemComponent'];
classNames?: Partial<AutocompleteIndexClassNames>;
};

Expand All @@ -71,7 +68,7 @@ export type AutocompleteProps<TItem extends BaseHit> = ComponentProps<'div'> & {
showSuggestions?: Partial<
Pick<
IndexConfig<{ query: string }>,
'indexName' | 'itemComponent' | 'classNames'
'indexName' | 'headerComponent' | 'itemComponent' | 'classNames'
>
>;
classNames?: Partial<AutocompleteClassNames>;
Expand All @@ -98,9 +95,10 @@ export function EXPERIMENTAL_Autocomplete<TItem extends BaseHit = BaseHit>({
if (showSuggestions?.indexName) {
indicesConfig.unshift({
indexName: showSuggestions.indexName,
// Temporarily force casting until the coming refactoring
headerComponent:
showSuggestions.headerComponent as unknown as AutocompleteIndexProps<TItem>['HeaderComponent'],
itemComponent: (showSuggestions.itemComponent ||
AutocompleteSuggestion) as unknown as ItemComponentProps<TItem>,
AutocompleteSuggestion) as unknown as AutocompleteIndexProps<TItem>['ItemComponent'],
classNames: {
root: cx(
'ais-AutocompleteSuggestions',
Expand All @@ -110,6 +108,10 @@ export function EXPERIMENTAL_Autocomplete<TItem extends BaseHit = BaseHit>({
'ais-AutocompleteSuggestionsList',
showSuggestions?.classNames?.list
),
header: cx(
'ais-AutocompleteSuggestionsHeader',
showSuggestions?.classNames?.header
),
item: cx(
'ais-AutocompleteSuggestionsItem',
showSuggestions?.classNames?.item
Expand Down Expand Up @@ -162,6 +164,8 @@ function InnerAutocomplete<TItem extends BaseHit = BaseHit>({
<AutocompleteIndex
key={indexId}
// @ts-expect-error - there seems to be problems with React.ComponentType and this, but it's actually correct
HeaderComponent={indicesConfig[index].headerComponent}
// @ts-expect-error - there seems to be problems with React.ComponentType and this, but it's actually correct
ItemComponent={indicesConfig[index].itemComponent}
items={hits.map((item) => ({
...item,
Expand Down
2 changes: 2 additions & 0 deletions tests/common/widgets/autocomplete/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { fakeAct, skippableDescribe } from '../../common';

import { createOptionsTests } from './options';
import { createTemplatesTests } from './templates';

import type { TestOptions, TestSetup } from '../../common';
import type { AutocompleteConnectorParams } from 'instantsearch.js/es/connectors/autocomplete/connectAutocomplete';
Expand Down Expand Up @@ -38,6 +39,7 @@ export function createAutocompleteWidgetTests(

skippableDescribe('Autocomplete widget common tests', skippedTests, () => {
createOptionsTests(setup, { act, skippedTests, flavor });
createTemplatesTests(setup, { act, skippedTests, flavor });
});
}
createAutocompleteWidgetTests.flavored = true;
123 changes: 123 additions & 0 deletions tests/common/widgets/autocomplete/templates.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import {
createMultiSearchResponse,
createSearchClient,
createSingleSearchResponse,
} from '@instantsearch/mocks';
import { wait } from '@instantsearch/testutils';
import userEvent from '@testing-library/user-event';
import React from 'react';

import type { AutocompleteWidgetSetup } from '.';
import type { TestOptions } from '../../common';

export function createTemplatesTests(
setup: AutocompleteWidgetSetup,
{ act }: Required<TestOptions>
) {
describe('templates', () => {
test('renders indices headers', async () => {
const searchClient = createMockedSearchClient(
createMultiSearchResponse(
createSingleSearchResponse({
index: 'indexName2',
hits: [
{ objectID: '1', query: 'hello' },
{ objectID: '2', query: 'world' },
],
}),
// @ts-expect-error - ignore second response type
createSingleSearchResponse({
index: 'indexName',
hits: [
{ objectID: '1', name: 'Item 1' },
{ objectID: '2', name: 'Item 2' },
{ objectID: '3', name: 'Item 3' },
],
})
)
);

await setup({
instantSearchOptions: {
indexName: 'indexName',
searchClient,
},
widgetParams: {
javascript: {
indices: [
{
indexName: 'indexName',
templates: {
item: (props) => props.item.name,
header: (props) =>
`<span>${props.items.length} results</span>`,

Check warning on line 53 in tests/common/widgets/autocomplete/templates.tsx

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

tests/common/widgets/autocomplete/templates.tsx#L53

This template literal looks like HTML and has interpolated variables.
},
cssClasses: { header: 'HEADER' },
},
],
showSuggestions: {
indexName: 'indexName2',
templates: {
header: (props) => `<span>${props.items.length} results</span>`,

Check warning on line 61 in tests/common/widgets/autocomplete/templates.tsx

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

tests/common/widgets/autocomplete/templates.tsx#L61

This template literal looks like HTML and has interpolated variables.
},
cssClasses: { header: 'HEADER' },
},
},
react: {
indices: [
{
indexName: 'indexName',
itemComponent: (props) => props.item.name,
headerComponent: (props) => (
<span>{props.items.length} results</span>
),
classNames: { header: 'HEADER' },
},
],
showSuggestions: {
indexName: 'indexName2',
headerComponent: (props) => (
<span>{props.items.length} results</span>
),
classNames: { header: 'HEADER' },
},
},
vue: {},
},
});

await act(async () => {
await wait(0);
// JS currently doesn't refine on focus
const input = document.querySelector('.ais-SearchBox-input')!;
userEvent.click(input);
userEvent.type(input, 'a');
userEvent.clear(input);

await wait(0);
});

const headers = [
...document.querySelectorAll('.ais-AutocompleteIndexHeader'),
];
expect(headers).toHaveLength(2);
expect(headers.map((header) => header.className)).toEqual([
'ais-AutocompleteIndexHeader ais-AutocompleteSuggestionsHeader HEADER',
'ais-AutocompleteIndexHeader HEADER',
]);
expect(headers.map((header) => header.textContent)).toEqual([
'2 results',
'3 results',
]);
});
});
}

function createMockedSearchClient(
response: ReturnType<typeof createMultiSearchResponse>
) {
return createSearchClient({
// @ts-expect-error - doesn't properly handle multi index, expects all responses to be of the same type
search: jest.fn(() => Promise.resolve(response)),
});
}