Files
investor-flow/app/src/lib/useKeyboardShortcuts.ts
T

40 lines
1.2 KiB
TypeScript
Raw Normal View History

"use client";
import { useEffect } from "react";
interface KeyboardShortcut {
key: string;
ctrl?: boolean;
shift?: boolean;
alt?: boolean;
handler: (e: KeyboardEvent) => void;
// Only fire when no input/modal is focused
when?: () => boolean;
}
/**
* Shared keyboard shortcut hook.
* Registers shortcuts at the LayoutShell level (closest to root).
* Uses keydown events with preventDefault only when needed.
*/
export function useKeyboardShortcuts(shortcuts: KeyboardShortcut[]) {
useEffect(() => {
const handler = (e: KeyboardEvent) => {
for (const shortcut of shortcuts) {
const matchesKey = e.key === shortcut.key;
const matchesCtrl = shortcut.ctrl ? e.ctrlKey || e.metaKey : !e.ctrlKey && !e.metaKey;
const matchesShift = shortcut.shift ? e.shiftKey : !e.shiftKey;
const matchesAlt = shortcut.alt ? e.altKey : !e.altKey;
if (matchesKey && matchesCtrl && matchesShift && matchesAlt) {
if (shortcut.when && !shortcut.when()) continue;
e.preventDefault();
shortcut.handler(e);
}
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [shortcuts]);
}