diff --git a/change/@fluentui-react-menu-be54a5cf-5794-430d-a10e-a84b223e4eef.json b/change/@fluentui-react-menu-be54a5cf-5794-430d-a10e-a84b223e4eef.json new file mode 100644 index 0000000000000..f79a030127fb3 --- /dev/null +++ b/change/@fluentui-react-menu-be54a5cf-5794-430d-a10e-a84b223e4eef.json @@ -0,0 +1,7 @@ +{ + "type": "patch", + "comment": "fix: Menu triggers no longer take focus when they are mounted", + "packageName": "@fluentui/react-menu", + "email": "behowell@microsoft.com", + "dependentChangeType": "patch" +} diff --git a/packages/react-components/react-menu/e2e/Menu.e2e.tsx b/packages/react-components/react-menu/e2e/Menu.e2e.tsx index f8ead57d4a120..cc3b17acc4a9c 100644 --- a/packages/react-components/react-menu/e2e/Menu.e2e.tsx +++ b/packages/react-components/react-menu/e2e/Menu.e2e.tsx @@ -115,6 +115,22 @@ describe('MenuTrigger', () => { cy.get(menuSelector).should('be.visible').get(menuItemSelector).first().should('be.focused'); }); }); + + it('should not automatically focus itself when mounted', () => { + mount( + + + + + + + Item + + + , + ); + cy.get(menuTriggerSelector).should('not.be.focused'); + }); }); describe('Custom Trigger', () => { diff --git a/packages/react-components/react-menu/src/components/Menu/useMenu.tsx b/packages/react-components/react-menu/src/components/Menu/useMenu.tsx index d81699a2f40ab..9264828f7397a 100644 --- a/packages/react-components/react-menu/src/components/Menu/useMenu.tsx +++ b/packages/react-components/react-menu/src/components/Menu/useMenu.tsx @@ -162,6 +162,7 @@ const useMenuOpenState = ( const parentSetOpen = useMenuContext_unstable(context => context.setOpen); const onOpenChange: MenuState['onOpenChange'] = useEventCallback((e, data) => state.onOpenChange?.(e, data)); + const shouldHandleKeyboardRef = React.useRef(false); const shouldHandleTabRef = React.useRef(false); const pressedShiftRef = React.useRef(false); const setOpenTimeout = React.useRef(0); @@ -185,6 +186,7 @@ const useMenuOpenState = ( } if (e.type === 'keydown' && (e as React.KeyboardEvent).key === Tab) { + shouldHandleKeyboardRef.current = true; shouldHandleTabRef.current = true; pressedShiftRef.current = (e as React.KeyboardEvent).shiftKey; } @@ -288,7 +290,7 @@ const useMenuOpenState = ( focusFirst(); } - if (!open) { + if (shouldHandleKeyboardRef.current && !open) { if (shouldHandleTabRef.current && !state.isSubmenu) { pressedShiftRef.current ? focusBeforeMenuTrigger() : focusAfterMenuTrigger(); } else { @@ -296,6 +298,7 @@ const useMenuOpenState = ( } } + shouldHandleKeyboardRef.current = false; shouldHandleTabRef.current = false; pressedShiftRef.current = false; }, [state.triggerRef, state.isSubmenu, open, focusFirst, focusAfterMenuTrigger, focusBeforeMenuTrigger]);