Files
convert-ui/lib/hooks/useKeyboardShortcuts.ts

66 lines
1.7 KiB
TypeScript
Raw Normal View History

import { useEffect } from 'react';
export interface KeyboardShortcut {
key: string;
ctrl?: boolean;
alt?: boolean;
shift?: boolean;
description: string;
action: () => void;
}
/**
* Hook for managing keyboard shortcuts
*/
export function useKeyboardShortcuts(shortcuts: KeyboardShortcut[], enabled: boolean = true) {
useEffect(() => {
if (!enabled) return;
const handleKeyDown = (event: KeyboardEvent) => {
// Find matching shortcut
const shortcut = shortcuts.find((s) => {
const keyMatch = s.key.toLowerCase() === event.key.toLowerCase();
const ctrlMatch = s.ctrl ? (event.ctrlKey || event.metaKey) : !event.ctrlKey && !event.metaKey;
const altMatch = s.alt ? event.altKey : !event.altKey;
const shiftMatch = s.shift ? event.shiftKey : !event.shiftKey;
return keyMatch && ctrlMatch && altMatch && shiftMatch;
});
if (shortcut) {
event.preventDefault();
shortcut.action();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [shortcuts, enabled]);
}
/**
* Format shortcut key combination for display
*/
export function formatShortcut(shortcut: KeyboardShortcut): string {
const parts: string[] = [];
// Use Cmd on Mac, Ctrl on others
const isMac = typeof window !== 'undefined' && /Mac|iPhone|iPod|iPad/.test(navigator.platform);
if (shortcut.ctrl) {
parts.push(isMac ? '⌘' : 'Ctrl');
}
if (shortcut.alt) {
parts.push(isMac ? '⌥' : 'Alt');
}
if (shortcut.shift) {
parts.push(isMac ? '⇧' : 'Shift');
}
parts.push(shortcut.key.toUpperCase());
return parts.join(' + ');
}