Skip to content

Commit 59852e5

Browse files
committed
conditionally add event listeners in search
1 parent 0fb5615 commit 59852e5

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

src/components/search/index.tsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import {usePathname, useRouter} from 'next/navigation';
1515
import algoliaInsights from 'search-insights';
1616

1717
import {useOnClickOutside} from 'sentry-docs/clientUtils';
18-
import {useKeyboardNavigate} from 'sentry-docs/hooks/useKeyboardNavigate';
18+
import {useListKeyboardNavigate} from 'sentry-docs/hooks/useListKeyboardNavigate';
1919
import {isDeveloperDocs} from 'sentry-docs/isDeveloperDocs';
2020

2121
import styles from './search.module.scss';
@@ -181,9 +181,10 @@ export function Search({path, autoFocus, searchPlatforms = [], showChatBot}: Pro
181181
[]
182182
);
183183

184-
const {focused} = useKeyboardNavigate({
184+
const {focused} = useListKeyboardNavigate({
185185
list: flatHits,
186186
onSelect: hit => router.push(relativizeUrl(hit.url)),
187+
disableEventListeners: !inputFocus,
187188
});
188189

189190
const trackSearchResultClick = useCallback((hit: Hit, position: number): void => {

src/hooks/useKeyboardNavigate.tsx renamed to src/hooks/useListKeyboardNavigate.tsx

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
import {useCallback, useEffect, useMemo, useState} from 'react';
22

33
type Props<T> = {
4+
/**
5+
* Whether to disable the keyboard event listeners conditionally
6+
*/
7+
disableEventListeners: boolean;
48
/**
59
* The list of values to navigate through
610
*/
711
list: T[];
12+
813
/**
914
* Callback triggered when the item is selected
1015
*/
@@ -14,7 +19,7 @@ type Props<T> = {
1419
/**
1520
* Navigate a list of items using the up/down arrow and ^j/^k keys
1621
*/
17-
function useKeyboardNavigate<T>({list, onSelect}: Props<T>) {
22+
function useListKeyboardNavigate<T>({list, onSelect, disableEventListeners}: Props<T>) {
1823
const [focused, setFocus] = useState<T | null>(null);
1924

2025
const setFocusIndex = useCallback(
@@ -85,11 +90,15 @@ function useKeyboardNavigate<T>({list, onSelect}: Props<T>) {
8590
);
8691

8792
useEffect(() => {
88-
document.addEventListener('keydown', handleNavigate);
89-
return () => document.removeEventListener('keydown', handleNavigate);
90-
}, [handleNavigate]);
93+
if (!disableEventListeners) {
94+
document.addEventListener('keydown', handleNavigate);
95+
return () => document.removeEventListener('keydown', handleNavigate);
96+
}
97+
98+
return undefined;
99+
}, [disableEventListeners, handleNavigate]);
91100

92101
return {focused, setFocus};
93102
}
94103

95-
export {useKeyboardNavigate};
104+
export {useListKeyboardNavigate};

0 commit comments

Comments
 (0)