Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
10 changes: 8 additions & 2 deletions examples/react/getting-started/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import {
InstantSearch,
Pagination,
RefinementList,
SearchBox,
TrendingItems,
Carousel,
Chat,
EXPERIMENTAL_Autocomplete,
} from 'react-instantsearch';

import { Panel } from './Panel';
Expand Down Expand Up @@ -55,7 +55,13 @@ export function App() {
</div>

<div className="search-panel__results">
<SearchBox placeholder="" className="searchbox" />
<EXPERIMENTAL_Autocomplete
showRecent
showSuggestions={{
indexName: 'instant_search_demo_query_suggestions',
}}
/>

<Hits hitComponent={HitComponent} />

<div className="pagination">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/** @jsx createElement */

import { cx } from '../../lib';

import type { Renderer } from '../../types';

export type AutocompleteRecentSearchProps<
T = { query: string } & Record<string, unknown>
> = {
item: T;
onSelect: () => void;
onRemoveRecentSearch: () => void;
classNames?: Partial<AutocompleteRecentSearchClassNames>;
};

export type AutocompleteRecentSearchClassNames = {
/**
* Class names to apply to the root element
**/
root: string | string[];
};

export function createAutocompleteRecentSearchComponent({
createElement,
}: Renderer) {
return function AutocompleteRecentSearch({
item,
onSelect,
onRemoveRecentSearch,
classNames = {},
}: AutocompleteRecentSearchProps) {
return (
<div
onClick={onSelect}
className={cx('ais-AutocompleteRecentSearch', classNames.root)}
>
{item.query}
<button
className={cx('ais-AutocompleteRecentSearchRemove')}
title={`Remove ${item.query} from recent searches`}
onClick={onRemoveRecentSearch}
/>
</div>
);
};
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './Autocomplete';
export * from './AutocompleteIndex';
export * from './AutocompletePanel';
export * from './AutocompleteRecentSearch';
export * from './AutocompleteSuggestion';
100 changes: 84 additions & 16 deletions packages/react-instantsearch/src/components/Autocomplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,22 @@ import {
createAutocompleteIndexComponent,
createAutocompletePanelComponent,
createAutocompleteSuggestionComponent,
createAutocompleteRecentSearchComponent,
cx,
} from 'instantsearch-ui-components';
import React, { createElement, useState, Fragment } from 'react';
import React, {
createElement,
useState,
Fragment,
useSyncExternalStore,
useRef,
} from 'react';
import { Index, useHits, useInstantSearch } from 'react-instantsearch-core';

import { SearchBox } from '../widgets/SearchBox';

import { createStorage } from './createStorage';

import type {
AutocompleteIndexClassNames,
Pragma,
Expand All @@ -36,9 +45,15 @@ const AutocompleteSuggestion = createAutocompleteSuggestionComponent({
Fragment,
});

const AutocompleteRecentSearch = createAutocompleteRecentSearchComponent({
createElement: createElement as Pragma,
Fragment,
});

type ItemComponentProps<TItem> = React.ComponentType<{
item: TItem;
onSelect: () => void;
classNames: Partial<AutocompleteIndexClassNames>;
}>;

type IndexConfig<TItem extends Hit<BaseHit> = Hit<BaseHit> | any> = {
Expand All @@ -62,14 +77,32 @@ export type AutocompleteProps = {
indexName?: string;
classNames?: Partial<AutocompleteIndexClassNames>;
};
showRecent?:
| boolean
| {
itemComponent: ItemComponentProps<{ query: string }> & {
onRemoveRecentSearch: () => void;
};
};
};

export function EXPERIMENTAL_Autocomplete({
indices: userIndices = [],
showSuggestions,
showRecent,
}: AutocompleteProps) {
const storageRef = useRef(createStorage({ limit: 5 }));
const storage = useSyncExternalStore(
(onStorageChange) => {
storageRef.current.registerUpdateListener(onStorageChange);
return () => {
storageRef.current.unregisterUpdateListener();
};
},
() => storageRef.current
);
const { indexUiState, setIndexUiState } = useInstantSearch();
const [isOpen, setIsOpen] = useState(false);
const { setIndexUiState } = useInstantSearch();

const indices = [...userIndices];

Expand Down Expand Up @@ -98,42 +131,77 @@ export function EXPERIMENTAL_Autocomplete({
});
}

const setQuery = (query: string) => {
storage.onAdd(query);
setIndexUiState((state) => ({ ...state, query }));
};

const query = indexUiState.query || '';

const AutocompleteRecentSearchComponent =
(typeof showRecent === 'object' && showRecent.itemComponent) ||
AutocompleteRecentSearch;

return (
<Index EXPERIMENTAL_isolated>
<Autocomplete isOpen={isOpen}>
<Autocomplete isOpen={isOpen}>
<Index EXPERIMENTAL_isolated>
<SearchBox onFocus={() => setIsOpen(true)} />
<AutocompletePanel isOpen={isOpen}>
{showRecent && (
<AutocompleteIndexComponent
setQuery={setQuery}
itemComponent={({ item, onSelect, classNames }) => (
<AutocompleteRecentSearchComponent
item={item}
onSelect={onSelect}
classNames={classNames}
onRemoveRecentSearch={() => storage.onRemove(item.query)}
/>
)}
classNames={{
root: 'ais-AutocompleteRecentSearches',
list: 'ais-AutocompleteRecentSearchesList',
item: 'ais-AutocompleteRecentSearchesItem',
}}
items={storage
.getAll(query)
.map((value) => ({ objectID: value, query: value }))}
/>
)}
{indices.map((index) => (
<Index key={index.indexName} indexName={index.indexName}>
<AutocompleteIndexComponent
{...index}
setQuery={(query) => {
setIndexUiState((state) => ({ ...state, query }));
}}
/>
<AutocompleteIndexComponent {...index} setQuery={setQuery} />
</Index>
))}
</AutocompletePanel>
</Autocomplete>
</Index>
</Index>
</Autocomplete>
);
}

function AutocompleteIndexComponent({
export function AutocompleteIndexComponent<
T extends { objectID: string } & Record<string, unknown> = {
objectID: string;
} & Record<string, unknown>
>({
itemComponent: ItemComponent,
onSelect,
getQuery,
getURL,
setQuery,
classNames,
}: IndexConfig & { setQuery: (query: string) => void }) {
const { items } = useHits();
items,
}: Omit<IndexConfig, 'indexName'> & {
setQuery: (query: string) => void;
items?: T[];
}) {
const { items: hits } = useHits();

return (
<AutocompleteIndex
// @ts-expect-error - there seems to be problems with React.ComponentType and this, but it's actually correct
ItemComponent={ItemComponent}
items={items}
items={items || hits}
onSelect={(item) => {
onSelect?.({
item,
Expand Down
68 changes: 68 additions & 0 deletions packages/react-instantsearch/src/components/createStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
const LOCAL_STORAGE_KEY_TEST = 'test-localstorage-support';
const LOCAL_STORAGE_KEY = 'autocomplete-recent-searches';

function isLocalStorageSupported() {
try {
localStorage.setItem(LOCAL_STORAGE_KEY_TEST, '');
localStorage.removeItem(LOCAL_STORAGE_KEY_TEST);

return true;
} catch (error) {
return false;
}
}

function getLocalStorage() {
if (!isLocalStorageSupported()) {
return {
setItems() {},
getItems() {
return [];
},
};
}

return {
setItems(items: string[]) {
try {
window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(items));
} catch {
// do nothing, this likely means the storage is full
}
},
getItems(): string[] {
const items = window.localStorage.getItem(LOCAL_STORAGE_KEY);

return items ? (JSON.parse(items) as string[]) : [];
},
};
}

export function createStorage({ limit = 5 }: { limit: number }) {
const storage = getLocalStorage();
let updateListener: (() => void) | null = null;

return {
onAdd(query: string) {
this.onRemove(query);
storage.setItems([query, ...storage.getItems()]);
},
onRemove(query: string) {
storage.setItems(storage.getItems().filter((q) => q !== query));

updateListener?.();
},
getAll(query = '') {
return storage
.getItems()
.filter((q) => q.includes(query))
.slice(0, limit);
},
registerUpdateListener(callback: () => void) {
updateListener = callback;
},
unregisterUpdateListener() {
updateListener = null;
},
};
}