apple2js/js/components/hooks/useHotKey.ts
Will Scullin 4a188a9a5c
Preact UI (#106)
First pass at a Preact UI, still short some major features but full proof of concept.
2022-05-10 06:52:06 -07:00

26 lines
751 B
TypeScript

import { useEffect } from 'preact/hooks';
/**
* Hook to allow registering hotkey that will automatically
* be cleaned up when they leave scope
*
* @param key KeyboardEvent key value to match
* @param callback Invoked when key is pressed
*/
export const useHotKey = (key: string, callback: (ev: KeyboardEvent) => void) => {
useEffect(() => {
const onKeyDown = (ev: KeyboardEvent) => {
if (ev.key === key) {
ev.preventDefault();
ev.stopPropagation();
callback(ev);
}
};
document.addEventListener('keydown', onKeyDown);
return () => {
document.removeEventListener('keydown', onKeyDown);
};
}, [key, callback]);
};