Created
November 9, 2021 07:10
-
-
Save tofusoup429/1a82fbd79a433eeb6f1e0d04b349f32f to your computer and use it in GitHub Desktop.
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
import { useEffect, useState } from 'react'; | |
type SubKey = 'Control'|'Alt'|'Tab'|'Shift'|'NN'; | |
type NodeEnv = 'production'|'development'|'test' | |
const useKeydown = (nodeEnv:NodeEnv):{subKey:SubKey, mainKey:string} => { | |
const [subKey, handleSubKey] = useState<'Control'|'Alt'|'Tab'|'Shift'|'NN'>('NN') | |
const [mainKey, handleMainKey] = useState<string>('') | |
useEffect(() => { | |
window.addEventListener('keydown', handleKeydown); | |
return () => removeEventListener('keydown', handleKeydown) | |
}, []); | |
const handleKeydown = (e: any) => { | |
if(nodeEnv === 'production') e.preventDefault(); | |
let key:string = e.key; | |
switch(key){ | |
case 'Control'||'Alt'||'Tab': | |
handleSubKey(key) | |
break; | |
default: | |
handleMainKey(key) | |
} | |
handleMainKey(e.key) | |
} | |
if(nodeEnv==='development') console.log('subKey', subKey, 'mainKey', mainKey) | |
return {subKey, mainKey} | |
} | |
export default useKeydown |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment