This repository has been archived by the owner on Jun 11, 2021. It is now read-only.
forked from algolia/autocomplete
-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(docsearch): add
useDocSearchKeyboardEvents
API
- Loading branch information
1 parent
295b81f
commit 5697895
Showing
3 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
26
packages/docsearch-react/src/useDocSearchKeyboardEvents.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); | ||
} |