Skip to content

Commit

Permalink
🐛Autocomplete: fix kb-navigation after scrolling (#3441)
Browse files Browse the repository at this point in the history
* 🐛Autocomplete: fix kb-navigation after scrolling

* also handle open via up/down arrows
  • Loading branch information
oddvernes authored May 14, 2024
1 parent 37c6dec commit 916bbb6
Showing 1 changed file with 30 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
EventHandler,
SyntheticEvent,
DOMAttributes,
FocusEvent,
} from 'react'
import {
useCombobox,
Expand Down Expand Up @@ -202,6 +203,21 @@ const findPrevIndex: IndexFinderType = ({
return prevIndex
}

/*When a user clicks the StyledList scrollbar, the input looses focus which breaks downshift
* keyboard navigation in the list. This code returns focus to the input on mouseUp
*/
const handleListFocus = (e: FocusEvent<HTMLElement>) => {
e.preventDefault()
e.stopPropagation()
window?.addEventListener(
'mouseup',
() => {
;(e.relatedTarget as HTMLInputElement)?.focus()
},
{ once: true },
)
}

const defaultOptionDisabled = () => false

type OptionLabelProps<T> = T extends string | number
Expand Down Expand Up @@ -530,6 +546,18 @@ function AutocompleteInner<T>(
},
onHighlightedIndexChange({ highlightedIndex, type }) {
if (
type == useCombobox.stateChangeTypes.InputClick ||
(type == useCombobox.stateChangeTypes.InputKeyDownArrowDown &&
!isOpen) ||
(type == useCombobox.stateChangeTypes.InputKeyDownArrowUp && !isOpen)
) {
//needs delay for dropdown to render before calling scroll
setTimeout(() => {
rowVirtualizer.scrollToIndex(highlightedIndex, {
align: allowSelectAll ? 'center' : 'auto',
})
}, 1)
} else if (
type !== useCombobox.stateChangeTypes.ItemMouseMove &&
type !== useCombobox.stateChangeTypes.MenuMouseLeave &&
highlightedIndex >= 0
Expand Down Expand Up @@ -767,7 +795,7 @@ function AutocompleteInner<T>(
}
}, [refs.reference, refs.floating, update, isOpen])

useEffect(() => {
useIsomorphicLayoutEffect(() => {
if (isOpen) {
refs.floating.current.showPopover()
} else {
Expand Down Expand Up @@ -797,6 +825,7 @@ function AutocompleteInner<T>(
popover="manual"
{...getFloatingProps({
ref: refs.setFloating,
onFocus: handleListFocus,
style: {
position: strategy,
top: y || 0,
Expand Down

0 comments on commit 916bbb6

Please sign in to comment.