@@ -417,15 +417,16 @@ export function SearchOverlay({
417417
418418 // Handle keyboard navigation of suggestions
419419 const handleKeyDown = ( event : React . KeyboardEvent < HTMLElement > ) => {
420+ let optionsLength = listElementsRef . current ?. length ?? 0
420421 if ( event . key === 'ArrowDown' ) {
421422 event . preventDefault ( )
422- if ( combinedOptions . length > 0 ) {
423+ if ( optionsLength > 0 ) {
423424 let newIndex = 0
424425 // If no item is selected, select the first item
425426 if ( selectedIndex === - 1 ) {
426427 newIndex = 0
427428 } else {
428- newIndex = ( selectedIndex + 1 ) % combinedOptions . length
429+ newIndex = ( selectedIndex + 1 ) % optionsLength
429430 // If we go "out of bounds" (i.e. the index is less than the selected index), unselect the item
430431 if ( newIndex < selectedIndex ) {
431432 newIndex = - 1
@@ -439,17 +440,23 @@ export function SearchOverlay({
439440 newIndex += 1
440441 }
441442 setSelectedIndex ( newIndex )
443+ if ( newIndex !== - 1 && listElementsRef . current [ newIndex ] ) {
444+ listElementsRef . current [ newIndex ] ?. scrollIntoView ( {
445+ behavior : 'smooth' ,
446+ block : 'center' ,
447+ } )
448+ }
442449 }
443450 } else if ( event . key === 'ArrowUp' ) {
444451 event . preventDefault ( )
445- if ( combinedOptions . length > 0 ) {
452+ if ( optionsLength > 0 ) {
446453 let newIndex = 0
447454 // If no item is selected, select the last item
448455 if ( selectedIndex === - 1 ) {
449- newIndex = combinedOptions . length - 1
456+ newIndex = optionsLength - 1
450457 } else {
451458 // Otherwise, select the previous item
452- newIndex = ( selectedIndex - 1 + combinedOptions . length ) % combinedOptions . length
459+ newIndex = ( selectedIndex - 1 + optionsLength ) % optionsLength
453460 // If we go "out of bounds" (i.e. the index is greater than the selected index), unselect the item
454461 if ( newIndex > selectedIndex ) {
455462 newIndex = - 1
@@ -464,6 +471,12 @@ export function SearchOverlay({
464471 newIndex -= 1
465472 }
466473 setSelectedIndex ( newIndex )
474+ if ( newIndex !== - 1 && listElementsRef . current [ newIndex ] ) {
475+ listElementsRef . current [ newIndex ] ?. scrollIntoView ( {
476+ behavior : 'smooth' ,
477+ block : 'center' ,
478+ } )
479+ }
467480 }
468481 } else if ( event . key === 'Enter' ) {
469482 event . preventDefault ( )
@@ -877,6 +890,7 @@ function renderSearchGroups(
877890 askAIEventGroupId = { askAIState . askAIEventGroupId }
878891 aiCouldNotAnswer = { askAIState . aiCouldNotAnswer }
879892 setAICouldNotAnswer = { askAIState . setAICouldNotAnswer }
893+ listElementsRef = { listElementsRef }
880894 />
881895 </ ActionList . Group > ,
882896 )
0 commit comments