-
Notifications
You must be signed in to change notification settings - Fork 553
feat(instantsearch.js): introduce autocomplete widget #6759
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
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
24dd275
create proper useAutocomplete hook
dhayab fd7d97e
move prop getters to ui components
dhayab 29e881d
refactor autocomplete react widget
dhayab 0c409ee
move react Autocomplete to widgets directory
dhayab f1164b1
implement js widget
dhayab df51a60
normalize ref between frameworks
dhayab 591c654
persist target index in renderstate + fix click on item
dhayab 8d43643
fixes for some of the failing tests
dhayab 3435e42
fix more tests
dhayab f278bca
bump bundlesize + some more typing shenanigans
dhayab bb9621b
Merge branch 'master' into feat/autocomplete-js-widget
dhayab File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
249 changes: 249 additions & 0 deletions
249
.../instantsearch-ui-components/src/components/autocomplete/createAutocompletePropGetters.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,249 @@ | ||
| import type { ComponentProps } from '../../types'; | ||
|
|
||
| type BaseHit = Record<string, unknown>; | ||
|
|
||
| export type AutocompleteIndexConfig<TItem extends BaseHit> = { | ||
| indexName: string; | ||
| getQuery?: (item: TItem) => string; | ||
| getURL?: (item: TItem) => string; | ||
| onSelect?: (params: { | ||
| item: TItem; | ||
| getQuery: () => string; | ||
| getURL: () => string; | ||
| setQuery: (query: string) => void; | ||
| }) => void; | ||
| }; | ||
|
|
||
| type GetInputProps = () => Partial<ComponentProps<'input'>>; | ||
|
|
||
| type GetItemProps = ( | ||
| item: { __indexName: string } & Record<string, unknown>, | ||
| index: number | ||
| ) => Pick<ComponentProps<'li'>, 'id' | 'role' | 'aria-selected'> & { | ||
| onSelect: () => void; | ||
| }; | ||
|
|
||
| type GetPanelProps = () => Pick< | ||
| ComponentProps<'div'>, | ||
| 'id' | 'hidden' | 'role' | 'aria-labelledby' | ||
| >; | ||
|
|
||
| type GetRootProps = () => Pick<ComponentProps<'div'>, 'ref'>; | ||
|
|
||
| type CreateAutocompletePropGettersParams = { | ||
| useEffect: (effect: () => void, inputs?: readonly unknown[]) => void; | ||
| useId: () => string; | ||
| useMemo: <TType>(factory: () => TType, inputs: readonly unknown[]) => TType; | ||
| useRef: <TType>(initialValue: TType | null) => { current: TType | null }; | ||
| useState: <TType>( | ||
| initialState: TType | ||
| ) => [TType, (newState: TType) => unknown]; | ||
| }; | ||
|
|
||
| type UsePropGetters<TItem extends BaseHit> = (params: { | ||
| indices: Array<{ | ||
| indexName: string; | ||
| indexId: string; | ||
| hits: Array<{ [key: string]: unknown }>; | ||
| }>; | ||
| indicesConfig: Array<AutocompleteIndexConfig<TItem>>; | ||
| onRefine: (query: string) => void; | ||
| }) => { | ||
| getInputProps: GetInputProps; | ||
| getItemProps: GetItemProps; | ||
| getPanelProps: GetPanelProps; | ||
| getRootProps: GetRootProps; | ||
| }; | ||
|
|
||
| export function createAutocompletePropGetters({ | ||
| useEffect, | ||
| useId, | ||
| useMemo, | ||
| useRef, | ||
| useState, | ||
| }: CreateAutocompletePropGettersParams) { | ||
| return function usePropGetters<TItem extends BaseHit>({ | ||
| indices, | ||
| indicesConfig, | ||
| onRefine, | ||
| }: Parameters<UsePropGetters<TItem>>[0]): ReturnType<UsePropGetters<TItem>> { | ||
| const getElementId = createGetElementId(useId()); | ||
| const rootRef = useRef<HTMLDivElement>(null); | ||
| const [isOpen, setIsOpen] = useState(false); | ||
| const [activeDescendant, setActiveDescendant] = useState< | ||
| string | undefined | ||
| >(undefined); | ||
|
|
||
| const { items, itemsIds } = useMemo( | ||
| () => buildItems({ indices, indicesConfig, getElementId }), | ||
| [indices, indicesConfig, getElementId] | ||
| ); | ||
|
|
||
| useEffect(() => { | ||
| const onBodyClick = (event: MouseEvent) => { | ||
| if (unwrapRef(rootRef)?.contains(event.target as HTMLElement)) { | ||
| return; | ||
| } | ||
|
|
||
| setIsOpen(false); | ||
| }; | ||
|
|
||
| document.body.addEventListener('click', onBodyClick); | ||
|
|
||
| return () => { | ||
| document.body.removeEventListener('click', onBodyClick); | ||
| }; | ||
| }, [rootRef]); | ||
|
|
||
| const getNextActiveDescendent = (key: string): string | undefined => { | ||
| switch (key) { | ||
| case 'ArrowLeft': | ||
| case 'ArrowUp': { | ||
| const prevIndex = itemsIds.indexOf(activeDescendant || '') - 1; | ||
| return itemsIds[prevIndex] || itemsIds[itemsIds.length - 1]; | ||
| } | ||
| case 'ArrowRight': | ||
| case 'ArrowDown': { | ||
| const nextIndex = itemsIds.indexOf(activeDescendant || '') + 1; | ||
| return itemsIds[nextIndex] || itemsIds[0]; | ||
| } | ||
| default: | ||
| return undefined; | ||
| } | ||
| }; | ||
|
|
||
| const submit = (actualActiveDescendant = activeDescendant) => { | ||
| setIsOpen(false); | ||
| if (actualActiveDescendant && items.has(actualActiveDescendant)) { | ||
| const { | ||
| item, | ||
| config: { onSelect, getQuery, getURL }, | ||
| } = items.get(actualActiveDescendant)!; | ||
| onSelect?.({ | ||
| item, | ||
| getQuery: () => getQuery?.(item) ?? '', | ||
| getURL: () => getURL?.(item) ?? '', | ||
| setQuery: (query) => onRefine(query), | ||
| }); | ||
| setActiveDescendant(undefined); | ||
| } | ||
| }; | ||
|
|
||
| return { | ||
| getInputProps: () => ({ | ||
| id: getElementId('input'), | ||
| role: 'combobox', | ||
| 'aria-autocomplete': 'list', | ||
| 'aria-expanded': isOpen, | ||
| 'aria-haspopup': 'grid', | ||
| 'aria-controls': getElementId('panel'), | ||
| 'aria-activedescendant': activeDescendant, | ||
| onFocus: () => setIsOpen(true), | ||
| onKeyDown: (event) => { | ||
| if (event.key === 'Escape') { | ||
| setActiveDescendant(undefined); | ||
| setIsOpen(false); | ||
| return; | ||
| } | ||
| switch (event.key) { | ||
| case 'ArrowLeft': | ||
| case 'ArrowUp': | ||
| case 'ArrowRight': | ||
| case 'ArrowDown': | ||
| setActiveDescendant(getNextActiveDescendent(event.key)); | ||
| event.preventDefault(); | ||
| break; | ||
| case 'Enter': { | ||
| submit(); | ||
| break; | ||
| } | ||
| case 'Tab': | ||
| setIsOpen(false); | ||
| break; | ||
| default: | ||
| return; | ||
| } | ||
| }, | ||
| onKeyUp: (event) => { | ||
| switch (event.key) { | ||
| case 'ArrowLeft': | ||
| case 'ArrowUp': | ||
| case 'ArrowRight': | ||
| case 'ArrowDown': | ||
| case 'Escape': | ||
| case 'Return': | ||
| event.preventDefault(); | ||
| return; | ||
| default: | ||
| setActiveDescendant(undefined); | ||
| break; | ||
| } | ||
| }, | ||
| }), | ||
| getItemProps: (item, index) => { | ||
| const id = getElementId('item', item.__indexName, index); | ||
|
|
||
| return { | ||
| id, | ||
| role: 'row', | ||
| 'aria-selected': id === activeDescendant, | ||
| onSelect: () => submit(id), | ||
| }; | ||
| }, | ||
| getPanelProps: () => ({ | ||
| hidden: !isOpen, | ||
| id: getElementId('panel'), | ||
| role: 'grid', | ||
| 'aria-labelledby': getElementId('input'), | ||
| }), | ||
| getRootProps: () => ({ | ||
| ref: rootRef, | ||
| }), | ||
| }; | ||
| }; | ||
| } | ||
|
|
||
| function buildItems<TItem extends BaseHit>({ | ||
| indices, | ||
| indicesConfig, | ||
| getElementId, | ||
| }: Pick<Parameters<UsePropGetters<TItem>>[0], 'indices' | 'indicesConfig'> & { | ||
| getElementId: ReturnType<typeof createGetElementId>; | ||
| }) { | ||
| const itemsIds = []; | ||
| const items = new Map< | ||
| string, | ||
| { item: TItem; config: AutocompleteIndexConfig<TItem> } | ||
| >(); | ||
|
|
||
| for (let i = 0; i < indicesConfig.length; i++) { | ||
| const config = indicesConfig[i]; | ||
| const hits = indices[i]?.hits || []; | ||
|
|
||
| for (let position = 0; position < hits.length; position++) { | ||
| const itemId = getElementId('item', config.indexName, position); | ||
| items.set(itemId, { | ||
| item: hits[position] as TItem, | ||
| config, | ||
| }); | ||
| itemsIds.push(itemId); | ||
| } | ||
| } | ||
| return { items, itemsIds }; | ||
| } | ||
|
|
||
| function createGetElementId(autocompleteId: string) { | ||
| return function getElementId(...suffixes: Array<string | number>) { | ||
| const prefix = 'autocomplete'; | ||
| return `${prefix}${autocompleteId}${suffixes.join(':')}`; | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Returns the framework-agnostic value of a ref. | ||
| */ | ||
| function unwrapRef<TType>(ref: { current: TType | null }): TType | null { | ||
| return ref.current && typeof ref.current === 'object' && 'base' in ref.current | ||
| ? (ref.current.base as TType) // Preact | ||
| : ref.current; // React | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think in a future PR, we could move these into a shared file. I believe there are some parts of the chat widgets that could use this approach.