@intility/bifrost-react
Version:
React library for Intility's design system, Bifrost.
33 lines (32 loc) • 1.22 kB
TypeScript
/**
* React hook for handling keyboard shortcuts (hotkeys) with Ctrl/⌘ + `key`.
*
* This hook listens for a specific key press combined with the platform's
* primary modifier key (Ctrl on Windows/Linux, ⌘ on macOS) and triggers the
* provided callback when the hotkey is pressed. It prevents the default browser
* behavior for the hotkey and ensures that no other modifier keys (like Shift,
* Alt) are pressed.
*
* @param key The key to listen for (e.g., `"k"` for Ctrl+K or ⌘+K).
* @param callback The function to call when the hotkey is triggered.
* Receives the KeyboardEvent as its argument.
* @returns An object containing:
* - `hotkeyText`: A string representation of the hotkey (e.g., `"Ctrl + K"`
* or `"⌘ + K"`).
*
* @example
* // focus search input on Ctrl/⌘ + K
* const { hotkeyText } = useHotkey("k", (e) => {
* inputRef.current?.focus();
* });
*
* @example
* // save data on Ctrl/⌘ + S
* const { hotkeyText } = useHotkey("s", (e) => {
* saveData();
* });
*/
declare function useHotkey<T extends string>(key: T, callback: (event: KeyboardEvent) => void): {
hotkeyText: `\u2318 + ${Uppercase<T>}` | `Ctrl + ${Uppercase<T>}`;
};
export default useHotkey;