Add keyboard shortcut for form submission and remove unused useEffect
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export function useKeyboardShortcut(
|
||||
callback: () => void,
|
||||
options: {
|
||||
ctrlOrCmd?: boolean;
|
||||
shift?: boolean;
|
||||
key?: string;
|
||||
disabled?: boolean;
|
||||
} = {}
|
||||
) {
|
||||
const {
|
||||
ctrlOrCmd = true,
|
||||
shift = false,
|
||||
key = 'Enter',
|
||||
disabled = false,
|
||||
} = options;
|
||||
|
||||
useEffect(() => {
|
||||
if (disabled) return;
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
const isKeyPressed = e.key === key;
|
||||
const isModifierPressed = ctrlOrCmd
|
||||
? (e.ctrlKey || e.metaKey) // Ctrl on Windows/Linux, Cmd on Mac
|
||||
: shift
|
||||
? e.shiftKey
|
||||
: false;
|
||||
|
||||
if (isKeyPressed && isModifierPressed) {
|
||||
e.preventDefault();
|
||||
callback();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||
}, [callback, ctrlOrCmd, shift, key, disabled]);
|
||||
}
|
||||
Reference in New Issue
Block a user