feat(docsearch): add useDocSearchKeyboardEvents API
This commit is contained in:
parent
ea9c7002de
commit
adadacd531
3 changed files with 38 additions and 0 deletions
|
|
@ -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)');
|
||||
|
||||
|
|
|
|||
|
|
@ -1,2 +1,3 @@
|
|||
export * from './DocSearchModal';
|
||||
export * from './DocSearchButton';
|
||||
export * from './useDocSearchKeyboardEvents';
|
||||
|
|
|
|||
26
src/useDocSearchKeyboardEvents.ts
Normal file
26
src/useDocSearchKeyboardEvents.ts
Normal 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]);
|
||||
}
|
||||
Loading…
Reference in a new issue