diff --git a/src/components/PopoverMenu.tsx b/src/components/PopoverMenu.tsx index 9b5c0b1b6f56b..f5b430499300a 100644 --- a/src/components/PopoverMenu.tsx +++ b/src/components/PopoverMenu.tsx @@ -137,6 +137,10 @@ const renderWithConditionalWrapper = (shouldUseScrollView: boolean, contentConta return <>{children}; }; +function getSelectedItemIndex(menuItems: PopoverMenuItem[]) { + return menuItems.findIndex((option) => option.isSelected); +} + function PopoverMenu({ menuItems, onItemSelected, @@ -174,7 +178,7 @@ function PopoverMenu({ // eslint-disable-next-line rulesdir/prefer-shouldUseNarrowLayout-instead-of-isSmallScreenWidth const {isSmallScreenWidth} = useResponsiveLayout(); const [currentMenuItems, setCurrentMenuItems] = useState(menuItems); - const currentMenuItemsFocusedIndex = currentMenuItems?.findIndex((option) => option.isSelected); + const currentMenuItemsFocusedIndex = getSelectedItemIndex(currentMenuItems); const [enteredSubMenuIndexes, setEnteredSubMenuIndexes] = useState(CONST.EMPTY_ARRAY); const {windowHeight} = useWindowDimensions(); @@ -300,7 +304,7 @@ function PopoverMenu({ ); const onModalHide = () => { - setFocusedIndex(-1); + setFocusedIndex(currentMenuItemsFocusedIndex); }; // When the menu items are changed, we want to reset the sub-menu to make sure @@ -312,7 +316,17 @@ function PopoverMenu({ } setEnteredSubMenuIndexes(CONST.EMPTY_ARRAY); setCurrentMenuItems(menuItems); - }, [menuItems]); + + // Update the focused item to match the selected item, but only when the popover is not visible. + // This ensures that if the popover is visible, highlight from the keyboard navigation is not overridden + // by external updates. + if (isVisible) { + return; + } + setFocusedIndex(getSelectedItemIndex(menuItems)); + + // eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps + }, [menuItems, setFocusedIndex]); return (