Skip to content

Commit

Permalink
fix: prevent pages from receiving KBarResults' keyboard events
Browse files Browse the repository at this point in the history
When interacting with KBarResults, `UpArrow`, `DownArrow`, and `Enter` keyboard events propagate, and can be received by the webpage underneath it. This patch invokes `stopPropagation()` on the events, and converts their listeners from bubbling to capturing, to ensure priority event handling.
  • Loading branch information
zenoamaro authored and timc1 committed Nov 14, 2023
1 parent 8ce425f commit 846b2c1
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/KBarResults.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export const KBarResults: React.FC<KBarResultsProps> = (props) => {

if (event.key === "ArrowUp" || (event.ctrlKey && event.key === "p")) {
event.preventDefault();
event.stopPropagation();
query.setActiveIndex((index) => {
let nextIndex = index > START_INDEX ? index - 1 : index;
// avoid setting active index on a group
Expand All @@ -62,6 +63,7 @@ export const KBarResults: React.FC<KBarResultsProps> = (props) => {
(event.ctrlKey && event.key === "n")
) {
event.preventDefault();
event.stopPropagation();
query.setActiveIndex((index) => {
let nextIndex =
index < itemsRef.current.length - 1 ? index + 1 : index;
Expand All @@ -74,15 +76,16 @@ export const KBarResults: React.FC<KBarResultsProps> = (props) => {
});
} else if (event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
// storing the active dom element in a ref prevents us from
// having to calculate the current action to perform based
// on the `activeIndex`, which we would have needed to add
// as part of the dependencies array.
activeRef.current?.click();
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
window.addEventListener("keydown", handler, {capture: true});
return () => window.removeEventListener("keydown", handler, {capture: true});
}, [query]);

// destructuring here to prevent linter warning to pass
Expand Down

1 comment on commit 846b2c1

@vercel
Copy link

@vercel vercel bot commented on 846b2c1 Nov 14, 2023

Choose a reason for hiding this comment

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

Successfully deployed to the following URLs:

kbar – ./

kbar.vercel.app
kbar-timc.vercel.app
kbar-git-main-timc.vercel.app

Please sign in to comment.