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

89 lines
2.7 KiB
TypeScript
Raw Permalink Normal View History

import { useEffect, useCallback } from 'react';
export interface KeyboardShortcut {
key: string;
ctrl?: boolean;
shift?: boolean;
alt?: boolean;
description: string;
action: () => void;
enabled?: boolean;
}
export interface UseKeyboardShortcutsOptions {
shortcuts: KeyboardShortcut[];
ignoreWhenInputFocused?: boolean;
}
/**
* Hook for managing keyboard shortcuts
* Automatically handles event listeners and cleanup
*/
export function useKeyboardShortcuts({
shortcuts,
ignoreWhenInputFocused = true,
}: UseKeyboardShortcutsOptions) {
const handleKeyDown = useCallback(
(event: KeyboardEvent) => {
// Ignore if typing in input/textarea/select
if (ignoreWhenInputFocused) {
const target = event.target as HTMLElement;
const tagName = target.tagName.toLowerCase();
const isEditable = target.isContentEditable;
if (
tagName === 'input' ||
tagName === 'textarea' ||
tagName === 'select' ||
isEditable
) {
// Allow ESC to blur inputs
if (event.key === 'Escape') {
target.blur();
}
return;
}
}
// Find matching shortcut
for (const shortcut of shortcuts) {
if (shortcut.enabled === false) continue;
const keyMatches = event.key.toLowerCase() === shortcut.key.toLowerCase();
const ctrlMatches = shortcut.ctrl ? event.ctrlKey || event.metaKey : !event.ctrlKey && !event.metaKey;
const shiftMatches = shortcut.shift ? event.shiftKey : !event.shiftKey;
const altMatches = shortcut.alt ? event.altKey : !event.altKey;
if (keyMatches && ctrlMatches && shiftMatches && altMatches) {
event.preventDefault();
shortcut.action();
break;
}
}
},
[shortcuts, ignoreWhenInputFocused]
);
useEffect(() => {
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [handleKeyDown]);
}
/**
* Common keyboard shortcuts for reference
*/
export const COMMON_SHORTCUTS = {
SEARCH: { key: '/', description: 'Focus search' },
REFRESH: { key: 'r', description: 'Refresh data' },
SELECT_ALL: { key: 'a', description: 'Select all' },
ESCAPE: { key: 'Escape', description: 'Clear selection / Close modal' },
HELP: { key: '?', shift: true, description: 'Show keyboard shortcuts' },
NEXT: { key: 'j', description: 'Next item' },
PREVIOUS: { key: 'k', description: 'Previous item' },
SELECT: { key: ' ', description: 'Toggle selection' },
START: { key: 's', description: 'Start selected' },
STOP: { key: 'x', description: 'Stop selected' },
RESTART: { key: 't', description: 'Restart selected' },
} as const;