1
0
Fork 0

feat(docsearch): add useDocSearchKeyboardEvents API

This commit is contained in:
François Chalifour 2020-05-14 12:27:28 +02:00
parent ea9c7002de
commit adadacd531
3 changed files with 38 additions and 0 deletions

View file

@ -65,6 +65,7 @@ export function DocSearchModal({
? window.getSelection()!.toString().slice(0, MAX_QUERY_SIZE)
: ''
).current;
const scrollY = React.useRef(0);
const searchClient = useSearchClient(appId, apiKey);
const favoriteSearches = React.useRef(
@ -279,6 +280,16 @@ export function DocSearchModal({
});
useTrapFocus({ container: containerRef.current });
React.useEffect(() => {
document.body.classList.add('DocSearch--active');
scrollY.current = window.scrollY;
return () => {
document.body.classList.remove('DocSearch--active');
window.scrollTop = scrollY.current;
};
}, []);
React.useEffect(() => {
const isMobileMediaQuery = window.matchMedia('(max-width: 750px)');

View file

@ -1,2 +1,3 @@
export * from './DocSearchModal';
export * from './DocSearchButton';
export * from './useDocSearchKeyboardEvents';

View file

@ -0,0 +1,26 @@
import React from 'react';
export function useDocSearchKeyboardEvents({ isOpen, onOpen, onClose }) {
React.useEffect(() => {
function onKeyDown(event: KeyboardEvent) {
if (
(event.keyCode === 27 && isOpen) ||
(event.key === 'k' && (event.metaKey || event.ctrlKey))
) {
event.preventDefault();
if (isOpen) {
onClose();
} else {
onOpen();
}
}
}
window.addEventListener('keydown', onKeyDown);
return () => {
window.removeEventListener('keydown', onKeyDown);
};
}, [isOpen, onOpen, onClose]);
}