Skip to content

Commit 2d9d711

Browse files
authored
fix: prevent pages from receiving KBarResults' keyboard events
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.
1 parent 8ce425f commit 2d9d711

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

src/KBarResults.tsx

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ export const KBarResults: React.FC<KBarResultsProps> = (props) => {
4848

4949
if (event.key === "ArrowUp" || (event.ctrlKey && event.key === "p")) {
5050
event.preventDefault();
51+
event.stopPropagation();
5152
query.setActiveIndex((index) => {
5253
let nextIndex = index > START_INDEX ? index - 1 : index;
5354
// avoid setting active index on a group
@@ -62,6 +63,7 @@ export const KBarResults: React.FC<KBarResultsProps> = (props) => {
6263
(event.ctrlKey && event.key === "n")
6364
) {
6465
event.preventDefault();
66+
event.stopPropagation();
6567
query.setActiveIndex((index) => {
6668
let nextIndex =
6769
index < itemsRef.current.length - 1 ? index + 1 : index;
@@ -74,15 +76,16 @@ export const KBarResults: React.FC<KBarResultsProps> = (props) => {
7476
});
7577
} else if (event.key === "Enter") {
7678
event.preventDefault();
79+
event.stopPropagation();
7780
// storing the active dom element in a ref prevents us from
7881
// having to calculate the current action to perform based
7982
// on the `activeIndex`, which we would have needed to add
8083
// as part of the dependencies array.
8184
activeRef.current?.click();
8285
}
8386
};
84-
window.addEventListener("keydown", handler);
85-
return () => window.removeEventListener("keydown", handler);
87+
window.addEventListener("keydown", handler, {capture: true});
88+
return () => window.removeEventListener("keydown", handler, {capture: true});
8689
}, [query]);
8790

8891
// destructuring here to prevent linter warning to pass

0 commit comments

Comments
 (0)