From adadacd53132a981d74c0764ea50b383383f42e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Thu, 14 May 2020 12:27:28 +0200 Subject: [PATCH] feat(docsearch): add `useDocSearchKeyboardEvents` API --- src/DocSearchModal.tsx | 11 +++++++++++ src/index.ts | 1 + src/useDocSearchKeyboardEvents.ts | 26 ++++++++++++++++++++++++++ 3 files changed, 38 insertions(+) create mode 100644 src/useDocSearchKeyboardEvents.ts diff --git a/src/DocSearchModal.tsx b/src/DocSearchModal.tsx index f5f78607d..85d6fb133 100644 --- a/src/DocSearchModal.tsx +++ b/src/DocSearchModal.tsx @@ -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)'); diff --git a/src/index.ts b/src/index.ts index f3a6716a5..ee6356a03 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,2 +1,3 @@ export * from './DocSearchModal'; export * from './DocSearchButton'; +export * from './useDocSearchKeyboardEvents'; diff --git a/src/useDocSearchKeyboardEvents.ts b/src/useDocSearchKeyboardEvents.ts new file mode 100644 index 000000000..f869ba8a4 --- /dev/null +++ b/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]); +}