33 */
44import { useEffect , useState } from 'react' ;
55
6- function useKeyPress ( targetKey : string , cb ?: ( ) => void ) : boolean {
6+ const decorateKey = ( { metaKey, ctrlKey, key } : KeyboardEvent ) => {
7+ if ( metaKey ) {
8+ return `meta+${ key } ` ;
9+ }
10+
11+ if ( ctrlKey ) {
12+ return `ctrl+${ key } ` ;
13+ }
14+
15+ return key ;
16+ } ;
17+
18+ interface UseKeyPressProps {
19+ targetKey : string ;
20+ callback ?: ( ) => void ;
21+ preventDefault ?: boolean ;
22+ }
23+
24+ function useKeyPress ( {
25+ targetKey,
26+ callback,
27+ preventDefault = false ,
28+ } : UseKeyPressProps ) : boolean {
729 const [ keyPressed , setKeyPressed ] = useState ( false ) ;
830
931 useEffect ( ( ) => {
10- const downHandler = ( { key } : KeyboardEvent ) => {
11- if ( key === targetKey ) {
32+ const downHandler = ( e : KeyboardEvent ) => {
33+ if ( decorateKey ( e ) === targetKey ) {
34+ if ( preventDefault ) {
35+ e . preventDefault ( ) ;
36+ }
1237 setKeyPressed ( true ) ;
13- if ( cb ) {
14- cb ( ) ;
38+ if ( typeof callback === 'function' ) {
39+ callback ( ) ;
1540 }
1641 }
1742 } ;
1843
19- const upHandler = ( { key } : KeyboardEvent ) => {
20- if ( key === targetKey ) {
44+ const upHandler = ( e : KeyboardEvent ) => {
45+ if ( decorateKey ( e ) === targetKey ) {
2146 setKeyPressed ( false ) ;
2247 }
2348 } ;
@@ -28,7 +53,7 @@ function useKeyPress(targetKey: string, cb?: () => void): boolean {
2853 window . removeEventListener ( 'keydown' , downHandler ) ;
2954 window . removeEventListener ( 'keyup' , upHandler ) ;
3055 } ;
31- } , [ cb , targetKey ] ) ;
56+ } , [ callback , targetKey , preventDefault ] ) ;
3257 return keyPressed ;
3358}
3459
0 commit comments