Skip to content

Commit adadacd

Browse files
feat(docsearch): add useDocSearchKeyboardEvents API
1 parent ea9c700 commit adadacd

3 files changed

Lines changed: 38 additions & 0 deletions

File tree

src/DocSearchModal.tsx

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ export function DocSearchModal({
6565
? window.getSelection()!.toString().slice(0, MAX_QUERY_SIZE)
6666
: ''
6767
).current;
68+
const scrollY = React.useRef(0);
6869

6970
const searchClient = useSearchClient(appId, apiKey);
7071
const favoriteSearches = React.useRef(
@@ -279,6 +280,16 @@ export function DocSearchModal({
279280
});
280281
useTrapFocus({ container: containerRef.current });
281282

283+
React.useEffect(() => {
284+
document.body.classList.add('DocSearch--active');
285+
scrollY.current = window.scrollY;
286+
287+
return () => {
288+
document.body.classList.remove('DocSearch--active');
289+
window.scrollTop = scrollY.current;
290+
};
291+
}, []);
292+
282293
React.useEffect(() => {
283294
const isMobileMediaQuery = window.matchMedia('(max-width: 750px)');
284295

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export * from './DocSearchModal';
22
export * from './DocSearchButton';
3+
export * from './useDocSearchKeyboardEvents';

src/useDocSearchKeyboardEvents.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import React from 'react';
2+
3+
export function useDocSearchKeyboardEvents({ isOpen, onOpen, onClose }) {
4+
React.useEffect(() => {
5+
function onKeyDown(event: KeyboardEvent) {
6+
if (
7+
(event.keyCode === 27 && isOpen) ||
8+
(event.key === 'k' && (event.metaKey || event.ctrlKey))
9+
) {
10+
event.preventDefault();
11+
12+
if (isOpen) {
13+
onClose();
14+
} else {
15+
onOpen();
16+
}
17+
}
18+
}
19+
20+
window.addEventListener('keydown', onKeyDown);
21+
22+
return () => {
23+
window.removeEventListener('keydown', onKeyDown);
24+
};
25+
}, [isOpen, onOpen, onClose]);
26+
}

0 commit comments

Comments
 (0)