Skip to content

Commit

Permalink
feat(docsearch): add useDocSearchKeyboardEvents API
Browse files Browse the repository at this point in the history
  • Loading branch information
francoischalifour committed May 14, 2020
1 parent ea9c700 commit adadacd
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/DocSearchModal.tsx
Expand Up @@ -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(
Expand Down Expand Up @@ -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)');

Expand Down
1 change: 1 addition & 0 deletions src/index.ts
@@ -1,2 +1,3 @@
export * from './DocSearchModal';
export * from './DocSearchButton';
export * from './useDocSearchKeyboardEvents';
26 changes: 26 additions & 0 deletions src/useDocSearchKeyboardEvents.ts
@@ -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]);
}

0 comments on commit adadacd

Please sign in to comment.