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

Prevent scrolling when a MenuItem is selected with the spacebar #6697

Merged
merged 3 commits into from
Feb 7, 2024
Merged
Changes from 1 commit
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
8 changes: 6 additions & 2 deletions packages/core/src/common/utils/domUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,10 @@ function throttleImpl<T extends Function>(
}

export function clickElementOnKeyPress(keys: string[]) {
return (e: React.KeyboardEvent) =>
keys.some(key => e.key === key) && e.target.dispatchEvent(new MouseEvent("click", { ...e, view: undefined }));
return (e: React.KeyboardEvent) => {
if (keys.some(key => e.key === key)) {
e.preventDefault(); // Prevent spacebar from scrolling the page
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this could possibly cause issues if a MenuItem has a text input inside it, I think. it's not really recommended, but I wouldn't be surprised if something like this exists in the wild:

https://codesandbox.io/p/devbox/distracted-cookies-sv5mlx

image

we should test / verify this behavior in the docs by adding an item which contains an <InputGroup> to the Menu docs example

one idea for preventing a regression here is to check if the keypress occurred in a text input, using another utility fn in this same module:

if (elementIsTextInput(e.target as HTMLElement)) {
  // don't prevent default
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I didn't consider someone could be nesting a text element in a MenuItem. I can add a check and docs example for that.

Though if that were the case today, it would be issuing a click on the MenuItem any time they hit the spacebar. I assume we'd want to keep that behavior to avoid any breaks?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it would be issuing a click on the MenuItem any time they hit the spacebar

Yeah I suppose so, but they might be doing their own preventDefault to work around this. Agree that we should preserve the existing behavior as much as possible to avoid surprises

e.target.dispatchEvent(new MouseEvent("click", { ...e, view: undefined }));
}
};
}