useHotKey
Registers keyboard shortcuts on window or a custom target.
Only the first matching hotkey runs, and the handler receives the original KeyboardEvent.
When the default window target is used in a browser, useHotKey makes document.body focusable with tabindex="-1" if it does not already have a tabindex. This lets close flows return focus to the page after a dialog, command palette, or other focus-trapping UI closes.
Importing
import { useHotKey } from '@almighty-shogun/common';Usage
import { useHotKey } from '@almighty-shogun/common';
const dispose = useHotKey('mod+k', () => {
// Open command palette.
});
dispose();Modifiers and keys
Hotkey strings are split on + and are case-insensitive. Aliases cover the awkward key names: ctrl, cmd, command, super, win, windows, option, opt, esc, return, del, up, down, left, right, space, spacebar, and plus.
mod is a portable modifier rather than an alias for one key: it matches Meta on Apple platforms and Control everywhere else, so mod+k is the usual way to write a command-palette shortcut.
Options
Every field of UseHotKeyOptions is optional, and the defaults live in the implementation rather than the type:
target— element, window, document, or component instance to listen on. Defaults towindow.enabled— when supplied and falsy, matching is skipped. Unset means always enabled.event—'keydown'or'keyup'. Defaults to'keydown'.preventDefault— callspreventDefault()on a match. Defaults totrue.stopPropagation— callsstopPropagation()on a match. Defaults tofalse.ignoreWhileTyping— skips shortcuts that use neither Control nor Meta while focus sits in an input, textarea, select, or content-editable element.Escapestill matches so focused dialogs and command palettes can close themselves. Defaults totrue.repeat— allows auto-repeat keydown events to match. Defaults tofalse.
Parameters
hotKeys: Arrayable<string>
Hotkey string or list of strings such as mod+k, escape, or shift+?.
handler: HotKeyHandler
Keyboard event handler called when a configured hotkey matches.
options?: UseHotKeyOptions
Registration and event-handling options.
Default: {}
Returns
A dispose function that removes the keyboard listener.Uses
Type signature
declare function useHotKey(
hotKeys: Arrayable<string>,
handler: HotKeyHandler,
options?: UseHotKeyOptions
): () => void;
type HotKeyHandler = (event: KeyboardEvent) => void;
type ComponentTarget = HTMLTarget | ComponentPublicInstance;
type UseHotKeyOptions = {
target?: MaybeRefOrGetter<NullableOrUndefinable<ComponentTarget>>;
enabled?: MaybeRefOrGetter<Undefinable<boolean>>;
event?: Undefinable<'keydown' | 'keyup'>;
preventDefault?: Undefinable<boolean>;
stopPropagation?: Undefinable<boolean>;
ignoreWhileTyping?: Undefinable<boolean>;
repeat?: Undefinable<boolean>;
};