Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Menu triggers no longer take focus when they are mounted #25016

Merged
merged 1 commit into from
Oct 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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"
}
16 changes: 16 additions & 0 deletions packages/react-components/react-menu/e2e/Menu.e2e.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<Menu>
<MenuTrigger>
<button>Menu</button>
</MenuTrigger>
<MenuPopover>
<MenuList>
<MenuItem>Item</MenuItem>
</MenuList>
</MenuPopover>
</Menu>,
);
cy.get(menuTriggerSelector).should('not.be.focused');
});
});

describe('Custom Trigger', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -185,6 +186,7 @@ const useMenuOpenState = (
}

if (e.type === 'keydown' && (e as React.KeyboardEvent<HTMLElement>).key === Tab) {
shouldHandleKeyboardRef.current = true;
shouldHandleTabRef.current = true;
pressedShiftRef.current = (e as React.KeyboardEvent<HTMLElement>).shiftKey;
}
Expand Down Expand Up @@ -288,14 +290,15 @@ const useMenuOpenState = (
focusFirst();
}

if (!open) {
if (shouldHandleKeyboardRef.current && !open) {
if (shouldHandleTabRef.current && !state.isSubmenu) {
pressedShiftRef.current ? focusBeforeMenuTrigger() : focusAfterMenuTrigger();
} else {
state.triggerRef.current?.focus();
}
}

shouldHandleKeyboardRef.current = false;
shouldHandleTabRef.current = false;
pressedShiftRef.current = false;
}, [state.triggerRef, state.isSubmenu, open, focusFirst, focusAfterMenuTrigger, focusBeforeMenuTrigger]);
Expand Down