35 lines
1.0 KiB
TypeScript
35 lines
1.0 KiB
TypeScript
|
|
'use client';
|
||
|
|
|
||
|
|
import { useEffect } from 'react';
|
||
|
|
|
||
|
|
export interface KeyboardShortcut {
|
||
|
|
key: string;
|
||
|
|
ctrlKey?: boolean;
|
||
|
|
metaKey?: boolean;
|
||
|
|
shiftKey?: boolean;
|
||
|
|
handler: () => void;
|
||
|
|
description: string;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function useKeyboardShortcuts(shortcuts: KeyboardShortcut[]) {
|
||
|
|
useEffect(() => {
|
||
|
|
const handleKeyDown = (event: KeyboardEvent) => {
|
||
|
|
for (const shortcut of shortcuts) {
|
||
|
|
const keyMatches = event.key.toLowerCase() === shortcut.key.toLowerCase();
|
||
|
|
const ctrlMatches = shortcut.ctrlKey ? event.ctrlKey || event.metaKey : !event.ctrlKey && !event.metaKey;
|
||
|
|
const metaMatches = shortcut.metaKey ? event.metaKey : true;
|
||
|
|
const shiftMatches = shortcut.shiftKey ? event.shiftKey : !event.shiftKey;
|
||
|
|
|
||
|
|
if (keyMatches && ctrlMatches && shiftMatches) {
|
||
|
|
event.preventDefault();
|
||
|
|
shortcut.handler();
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
window.addEventListener('keydown', handleKeyDown);
|
||
|
|
return () => window.removeEventListener('keydown', handleKeyDown);
|
||
|
|
}, [shortcuts]);
|
||
|
|
}
|