Skip to content
This repository has been archived by the owner on Jun 11, 2021. It is now read-only.

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 295b81f commit 5697895
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
11 changes: 11 additions & 0 deletions packages/docsearch-react/src/DocSearchModal.tsx
Original file line number Diff line number Diff line change
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 packages/docsearch-react/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './DocSearchModal';
export * from './DocSearchButton';
export * from './useDocSearchKeyboardEvents';
26 changes: 26 additions & 0 deletions packages/docsearch-react/src/useDocSearchKeyboardEvents.ts
Original file line number Diff line number Diff line change
@@ -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 5697895

Please sign in to comment.