Skip to content

Commit

Permalink
[DropdownMenu] Fix touch devices trigger bug
Browse files Browse the repository at this point in the history
  • Loading branch information
jasongerbes committed Nov 21, 2024
1 parent 4584a37 commit 6620b93
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
2 changes: 1 addition & 1 deletion .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ There are many ways to contribute to the project. Code is just one possible mean

## Working on your first Pull Request?

There are a lot of great resources on creating a good pull request. We've included a few below, but don't be shy—we appreciate all contriibutions and are happy to help those who are willing to help us!
There are a lot of great resources on creating a good pull request. We've included a few below, but don't be shy—we appreciate all contributions and are happy to help those who are willing to help us!

- [How to Contribute to a Project on GitHub](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)

Expand Down
15 changes: 13 additions & 2 deletions packages/react/dropdown-menu/src/DropdownMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ const DropdownMenuTrigger = React.forwardRef<DropdownMenuTriggerElement, Dropdow
const { __scopeDropdownMenu, disabled = false, ...triggerProps } = props;
const context = useDropdownMenuContext(TRIGGER_NAME, __scopeDropdownMenu);
const menuScope = useMenuScope(__scopeDropdownMenu);
const pointerTypeRef = React.useRef<React.PointerEvent['pointerType']>('touch');

return (
<MenuPrimitive.Anchor asChild {...menuScope}>
<Primitive.button
Expand All @@ -113,10 +115,19 @@ const DropdownMenuTrigger = React.forwardRef<DropdownMenuTriggerElement, Dropdow
disabled={disabled}
{...triggerProps}
ref={composeRefs(forwardedRef, context.triggerRef)}
onClick={composeEventHandlers(props.onClick, () => {
// Open on click when using a touch or pen device
if (!disabled && pointerTypeRef.current !== 'mouse') {
context.onOpenToggle();
}
})}
onPointerDown={composeEventHandlers(props.onPointerDown, (event) => {
pointerTypeRef.current = event.pointerType;

// only call handler if it's the left button (mousedown gets triggered by all mouse buttons)
// but not when the control key is pressed (avoiding MacOS right click)
if (!disabled && event.button === 0 && event.ctrlKey === false) {
// but not when the control key is pressed (avoiding MacOS right click); also not for touch
// devices because that would open the menu on scroll. (pen devices behave as touch on iOS).
if (!disabled && event.button === 0 && event.ctrlKey === false && event.pointerType === 'mouse') {
context.onOpenToggle();
// prevent trigger focusing when opening
// this allows the content to be given focus without competition
Expand Down

0 comments on commit 6620b93

Please sign in to comment.