mirror of
https://github.com/cpvalente/ontime.git
synced 2026-08-12 02:43:50 +00:00
a3487e7073
* 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
26 lines
751 B
TypeScript
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]);
|
|
};
|