Last active
August 12, 2023 14:35
-
-
Save jackbkennedy/d6f53f4aed3ba8c33ef8b1596e17463d to your computer and use it in GitHub Desktop.
useCapslock
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 {useState, useEffect, useCallback} from 'react'; | |
const EVENT_KEY_DOWN = 'keydown'; | |
const EVENT_KEY_UP = 'keyup'; | |
/* Hook to verify state of Caps Lock */ | |
export function useCaplocks(): boolean { | |
/* State for keeping track of whether caps lock is on */ | |
const [isCaplocksActive, setIsCapLocksActive] = useState<boolean>(false); | |
/* Function to see if caps lock was activated - returns a memorized callback */ | |
const wasCapsLockActivated = useCallback( | |
(event: KeyboardEvent) => { | |
if ( | |
event.getModifierState && | |
event.getModifierState('CapsLock') && | |
isCaplocksActive === false | |
) { | |
setIsCapLocksActive(true); | |
} | |
}, | |
[isCaplocksActive] | |
); | |
/* Function to see if caps lock was deactivated - returns a memorized callback */ | |
const wasCapsLockDeactivated = useCallback( | |
(event: KeyboardEvent) => { | |
if ( | |
event.getModifierState && | |
!event.getModifierState('CapsLock') && | |
isCaplocksActive === true | |
) { | |
setIsCapLocksActive(false); | |
} | |
}, | |
[isCaplocksActive] | |
); | |
useEffect(() => { | |
/* Add keydown event listener */ | |
document.addEventListener(EVENT_KEY_DOWN, wasCapsLockActivated); | |
/* Remove keydown event listener on cleanup */ | |
return () => { | |
document.removeEventListener(EVENT_KEY_DOWN, wasCapsLockActivated); | |
}; | |
}, [wasCapsLockActivated]); | |
useEffect(() => { | |
/* Add keyup event listener */ | |
document.addEventListener(EVENT_KEY_UP, wasCapsLockDeactivated); | |
return () => { | |
/* Remove keyup event listener on cleanup */ | |
document.removeEventListener(EVENT_KEY_UP, wasCapsLockDeactivated); | |
}; | |
}, [wasCapsLockDeactivated]); | |
return isCaplocksActive; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment