UNPKG

@intility/bifrost-react

Version:

React library for Intility's design system, Bifrost.

67 lines (66 loc) 2.34 kB
/** * Configuration object for defining keyboard shortcuts with explicit modifiers. */ export type HotkeyConfig = { /** Whether Ctrl/⌘ key should be pressed (maps to Ctrl on Windows/Linux, ⌘ on Mac, default: `true`) */ ctrlOrCmd?: boolean; /** Whether Shift key should be pressed (default: `false`) */ shift?: boolean; /** Whether Alt key should be pressed (default: `false`) */ alt?: boolean; /** Configure whether default browser/OS behavior for the hotkey should be prevented (default: `true`) */ preventDefault?: boolean; }; /** * React hook for handling keyboard shortcuts (hotkeys). * * Supports two APIs: * 1. useHotkey("k", callback) - Listens to "Ctrl/⌘ + key" * 2. useHotkey("k", callback, options) - "Ctrl/⌘ + key" is still default, but * provides options to add `shift` or `alt`, or turn off `ctrlOrCmd` and * `preventDefault` * * @param key - The key to listen for (e.g., "k", "Escape", "ArrowUp", "F1", " " for Space) * @param callback - Function called when hotkey is triggered * @param config - Optional configuration object provides options to add `shift` * or `alt`, or turn off `ctrlOrCmd` and `preventDefault` * @returns Object with hotkeyText for display purposes * * @see https://bifrost.intility.com/react/useHotkey * * @example * // Focus search input on Ctrl/⌘ + K * const { hotkeyText } = useHotkey("k", (e) => { * searchInputRef.current?.focus(); * }); * // `hotkeyText` will be "Ctrl + K" on win/linux, and "⌘ + K" on macos * * @example * // Save on Ctrl/⌘ + S * const { hotkeyText } = useHotkey("s", (e) => { * save(); * }); * * @example * // Save all with Ctrl/⌘ + Shift/⇧ + S * const { hotkeyText } = useHotkey("s", (e) => { * saveAll(); * }, { shift: true }); * // `hotkeyText` will be "Ctrl + Shift + S" on win/linux, and "⌘ + ⇧ + S" on macos * * @example * // Escape (no modifiers) * const { hotkeyText } = useHotkey("Escape", (e) => { * cancel(); * }, { ctrlOrCmd: false }); * * @example * // Special keys - Escape (no modifiers) * const { hotkeyText } = useHotkey("Escape", (e) => { * cancel(); * }, { ctrlOrCmd: false }); */ declare function useHotkey(key: string, callback: (event: KeyboardEvent) => void, config?: HotkeyConfig): { hotkeyText: string; }; export default useHotkey;