@hyperse/tinykeys
Version:
This library registers and listens to keyboard input, executing actions when the keystrokes match a user-defined shortcut.
104 lines (99 loc) • 2.98 kB
TypeScript
/**
* A map of keybinding strings to event handlers.
*/
interface KeyBindingMap {
[keybinding: string]: (event: KeyboardEvent) => void;
}
/**
* Options to configure the behavior of keybindings.
*/
interface KeyBindingOptions {
/**
* Key presses will listen to this event (default: "keydown").
*/
event?: 'keydown' | 'keyup';
/**
* Keybinding sequences will wait this long between key presses before
* cancelling (default: 1000).
*
* **Note:** Setting this value too low (i.e. `300`) will be too fast for many
* of your users.
*/
timeout?: number;
}
/**
* Subscribes to keybindings.
*
* Returns an unsubscribe method.
*
* @example
* ```js
* import { keybindings } from "../src/keybindings"
*
* keybindings(window, {
* "Shift+d": () => {
* alert("The 'Shift' and 'd' keys were pressed at the same time")
* },
* "y e e t": () => {
* alert("The keys 'y', 'e', 'e', and 't' were pressed in order")
* },
* "$mod+d": () => {
* alert("Either 'Control+d' or 'Meta+d' were pressed")
* },
* })
* ```
*/
declare function keybindings(target: Window | HTMLElement, keyBindingMap: KeyBindingMap, options?: KeyBindingOptions): () => void;
declare function testPlatform(re: RegExp): boolean;
declare const isMac: () => boolean;
declare const isIPhone: () => boolean;
declare const isIPod: () => boolean;
declare const isIPad: () => boolean;
declare const isIOS: () => boolean;
declare const isAppleDevice: () => boolean;
declare function isModKey(event: KeyboardEvent | MouseEvent): boolean;
type shouldRejectKeystrokesProps = {
ignoreWhenFocused: string[];
};
declare function shouldRejectKeystrokes(props?: shouldRejectKeystrokesProps): boolean | null;
type Action = {
/**
* Unique identifier for the action
*/
id: string;
/**
* `Shift+d`: The 'Shift' and 'd' keys were pressed at the same time
* `y e e t`: The keys 'y', 'e', 'e', and 't' were pressed in order
* `$mod+d`: Either 'Control+d' or 'Meta+d' were pressed
*/
shortcut?: string[];
};
type UseTinykeysProps<T extends Action> = {
actionTree: Record<string, T>;
onActionSelect: (action: T) => void;
options?: KeyBindingOptions;
};
/**
* `useTinykeys` registers and listens to keyboard strokes and
* performs actions for patterns that match the user defined `shortcut`.
*
* @example
* ```tsx
* const bindingEvents = useTinykeys({
* actionTree: {
* search: {
* id: 'search',
* shortcut: ['$mod+k'],
* },
* },
* onActionSelect: (action) => {
* console.log(action);
* },
* options: {
* timeout: 400,
* },
* });
* ```
*/
declare function useTinykeys<T extends Action>(props: UseTinykeysProps<T>): () => () => void;
export { type Action, type KeyBindingMap, type KeyBindingOptions, type UseTinykeysProps, isAppleDevice, isIOS, isIPad, isIPhone, isIPod, isMac, isModKey, keybindings, shouldRejectKeystrokes, testPlatform, useTinykeys };