From bcfcf299ece542318dc073e4d332a582f3f0aaba Mon Sep 17 00:00:00 2001 From: glenngijsberts Date: Tue, 27 Sep 2022 16:13:31 +0200 Subject: [PATCH] fix(SelectV2): scroll element into view when using arrow keys This makes sure that we don't use the native element scrolling behavior but rather scroll to an element when it's getting focussed. This makes the scrolling behavior using arrow keys a bit nicer. --- src/components/SelectV2/DesktopDropdown.tsx | 30 ++++++++++++++++++--- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/components/SelectV2/DesktopDropdown.tsx b/src/components/SelectV2/DesktopDropdown.tsx index 03567b9f..25319498 100644 --- a/src/components/SelectV2/DesktopDropdown.tsx +++ b/src/components/SelectV2/DesktopDropdown.tsx @@ -145,12 +145,34 @@ export const DesktopDropdown = ({ setFocussed(options.length - 1) break case 'ArrowUp': - setFocussed(focussed => Math.max(0, focussed - 1)) + event.preventDefault() + + setFocussed(previousFocussed => { + const focussed = Math.max(0, previousFocussed - 1) + + scrollIntoView(listbox.children[focussed], { + boundary: listbox, + scrollMode: 'always', + block: 'nearest', + }) + + return focussed + }) break case 'ArrowDown': - setFocussed(focussed => - Math.min(options.length - 1, focussed + 1) - ) + event.preventDefault() + + setFocussed(prevFocussed => { + const focussed = Math.min(options.length - 1, prevFocussed + 1) + + scrollIntoView(listbox.children[focussed], { + boundary: listbox, + scrollMode: 'always', + block: 'nearest', + }) + + return focussed + }) break case 'Escape': setOpen(false)