27 lines
709 B
JavaScript
27 lines
709 B
JavaScript
import { useEffect } from 'react';
|
|
|
|
export const useHotkeyFocus = (ref, hotkey = 'k') => {
|
|
useEffect(() => {
|
|
if (!ref?.current) return;
|
|
|
|
const handleKeyPress = (event) => {
|
|
const isHotkey = event.key.toLowerCase() === hotkey.toLowerCase();
|
|
|
|
// CTRL + Hotkey
|
|
if (isHotkey && (event.metaKey || event.ctrlKey)) {
|
|
event.preventDefault();
|
|
ref.current?.focus();
|
|
}
|
|
|
|
// ESC to blur
|
|
if (event.key === 'Escape' && document.activeElement === ref.current) {
|
|
ref.current.blur();
|
|
}
|
|
};
|
|
|
|
document.addEventListener('keydown', handleKeyPress);
|
|
|
|
return () => document.removeEventListener('keydown', handleKeyPress);
|
|
}, [ref, hotkey]);
|
|
};
|