Add keyboard shortcut for form submission and remove unused useEffect

This commit is contained in:
Riccardo Giorato
2025-12-26 19:29:49 +01:00
parent 85f18f0ed1
commit ab3885eaa1
4 changed files with 60 additions and 28 deletions
+39
View File
@@ -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]);
}