turash/bugulma/frontend/hooks/useKeyboard.ts
Damir Mukimov 28f06d5787
Some checks failed
CI/CD Pipeline / backend-lint (push) Failing after 31s
CI/CD Pipeline / backend-build (push) Has been skipped
CI/CD Pipeline / frontend-lint (push) Failing after 1m22s
CI/CD Pipeline / frontend-build (push) Has been skipped
CI/CD Pipeline / e2e-test (push) Has been skipped
fix: resolve React Compiler and linting errors
- Fix React Compiler memoization issues in useOrganizationPage.ts
- Replace useCallback with useRef pattern in useKeyboard.ts
- Remove unnecessary dependencies from useMemo hooks
- Fix prettier formatting in api-client.ts and api-config.ts
- Replace any types with proper types in error-handling, http-client, security
- Remove unused imports and variables
- Move ImpactBreakdownChart component outside render in ImpactMetrics.tsx
- Fix setState in effect by using useMemo in HeritageBuildingPage.tsx
- Memoize getHistoryTitle with useCallback in MatchDetailPage and MatchNegotiationPage
- Add i18n for literal strings in community pages and LoginPage
- Fix missing dependencies in DashboardPage and DiscoveryPage
2025-12-25 00:21:47 +01:00

50 lines
1.1 KiB
TypeScript

import { useEffect, useRef } from 'react';
interface UseKeyboardOptions {
enabled?: boolean;
target?: EventTarget;
}
/**
* Hook for handling keyboard events with automatic cleanup
*/
export function useKeyboard(
handler: (event: KeyboardEvent) => void,
options: UseKeyboardOptions = {}
) {
const { enabled = true, target = document } = options;
const handlerRef = useRef(handler);
// Update handler ref when handler changes
useEffect(() => {
handlerRef.current = handler;
}, [handler]);
useEffect(() => {
if (!enabled) return;
const wrappedHandler = (event: KeyboardEvent) => {
handlerRef.current(event);
};
target.addEventListener('keydown', wrappedHandler);
return () => target.removeEventListener('keydown', wrappedHandler);
}, [enabled, target]);
}
/**
* Hook for handling escape key with a callback
*/
export function useEscapeKey(onEscape: () => void, options: UseKeyboardOptions = {}) {
const handleKeyDown = useCallback(
(event: KeyboardEvent) => {
if (event.key === 'Escape') {
onEscape();
}
},
[onEscape]
);
useKeyboard(handleKeyDown, options);
}