Files
ontime/apps/client/src/common/hooks/useKeyDown.ts
T
Carlos Valente a3487e7073 v2 cleanup (#427)
* refactor: remove useless template

* refactor: handle promise

* refactor: associate labels to fields

* refactor: simplify checking if element exists

* refactor: prevent reassigning

* refactor: avoid wildcard imports

* refactor: simplify imports

* refactor: simplify boolean comparison

* chore: version bump
2023-06-05 20:52:09 +02:00

26 lines
751 B
TypeScript

import { useCallback, useEffect } from 'react';
type UseKeyDown = (callback: () => void, targetKey: string, options?: { isDisabled?: boolean }) => void;
export const useKeyDown: UseKeyDown = (callback, targetKey, options = {}) => {
const { isDisabled = false } = options;
const onKeyDown = useCallback(
(event: KeyboardEvent) => {
const targetKeyPressed = event.key === targetKey && !event.repeat;
if (targetKeyPressed && !isDisabled) {
event.preventDefault();
callback();
}
},
[callback, isDisabled, targetKey],
);
useEffect(() => {
document.addEventListener('keydown', onKeyDown);
return () => {
document.removeEventListener('keydown', onKeyDown);
};
}, [onKeyDown]);
};