@keybindy/react
Version:
Keybindy for React: Simple, scoped keyboard shortcuts that require little setup. designed to smoothly blend in with your React applications, allowing for robust keybinding functionality without the overhead.
217 lines (212 loc) • 7.45 kB
TypeScript
import React from 'react';
import ShortcutManager, { Keys, ShortcutHandler, ShortcutOptions, Shortcut } from '@keybindy/core';
import * as react_jsx_runtime from 'react/jsx-runtime';
/**
* Represents a keyboard shortcut definition.
*/
type ShortcutDefinition = {
/**
* The key combination(s) to listen for.
* Can be a single array of keys or an array of key combinations.
*/
keys: Keys[] | Keys[][];
/**
* Callback function to invoke when the shortcut is triggered.
*/
handler: ShortcutHandler;
/**
* Optional configuration, including scope and other metadata.
*/
options?: Omit<ShortcutOptions, 'scope'>;
};
/**
* Props for the `<Keybindy />` component.
*/
type KeybindyProps = {
/**
* The scope under which the shortcuts should be active.
* This allows managing different contexts for shortcuts.
*/
scope: string;
/**
* Array of shortcut definitions to register for this scope.
*/
shortcuts?: ShortcutDefinition[];
/**
* Whether the shortcuts should be disabled for this scope.
* Defaults to `false`.
*/
disabled?: boolean;
/**
* Callback function that will be called when a shortcut is fired.
* Receives the fired shortcut info as an argument.
*/
onShortcutFired?: (info: Shortcut) => void;
/**
* Whether to enable debug logs in the console.
*/
logs?: boolean;
/**
* The content that will be rendered inside the Shortcut component.
*/
children: React.ReactNode;
};
/**
* `<Keybindy />` is a React component that registers keyboard shortcuts within a given scope. It allows
* users to define custom shortcuts and their associated handlers, while managing scope-based shortcut behavior.
* The component listens for keyboard events and triggers the registered handler when the corresponding keys are pressed.
* It also provides an optional callback (`onShortcutFired`) to notify users when a shortcut is triggered.
*
* @component
*
* @example
* // Basic usage
* <Keybindy scope="global" shortcuts={[{ keys: ['ctrl', 's'], handler: saveDocument }]} >
* <div>Content with shortcuts</div>
* </Keybindy>
*
* @example
* // With custom callback for onShortcutFired
* <Keybindy
* scope="editor"
* shortcuts={[{ keys: ['ctrl', 'e'], handler: editDocument }]}
* onShortcutFired={(info) => console.log('Shortcut fired:', info)}
* >
* <div>Editor with shortcuts</div>
* </Keybindy>
*
* @param {ShortcutProps} props - Props for the Shortcut component.
* @param {string} props.scope - The scope under which the shortcuts should be active.
* @param {ShortcutDefinition[]} [props.shortcuts] - An array of shortcut definitions, each containing keys, handler, and options.
* @param {boolean} [props.disabled=false] - Whether the shortcuts should be disabled for this scope.
* @param {(info: Shortcut) => void} [props.onShortcutFired] - Optional callback triggered when a shortcut is fired, providing the shortcut info.
* @param {React.ReactNode} props.children - The children to be rendered inside the component, which can contain any JSX elements.
*
* @returns {JSX.Element} The rendered component with registered shortcuts within the provided scope.
*/
declare const Keybindy: React.FC<KeybindyProps>;
interface ShortcutLabelProps extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> {
/**
* Array of keys to display
*/
keys: Omit<Keys, 'Ctrl (Left)' | 'Ctrl (Right)' | 'Shift (Left)' | 'Shift (Right)' | 'Alt (Left)' | 'Alt (Right)' | 'Meta (Left)' | 'Meta (Right)'>[];
/**
* Custom render function for each key
*/
renderKey?: (
/**
* The key to render
*/
key: string,
/**
* The index of the key in the array
*/
index: number,
/**
* All keys in the array
*/
allKeys: string[]) => React.ReactNode;
}
/**
* `<ShortcutLabel />` is a utility React component that visually renders a keyboard shortcut label.
*
* It accepts an array of keys (e.g. `["Ctrl", "S"]`) and renders a styled label using platform-aware
* symbols (⌘ for Mac, Ctrl for others). Users can also provide a custom render function to override
* the default display logic for advanced layouts or custom themes.
*
* @component
*
* @example
* // Default usage
* <ShortcutLabel keys={['ctrl', 's']} />
*
* @example
* // With custom renderKey
* <ShortcutLabel
* keys={['ctrl', 'alt', 'delete']}
* renderKey={(key, i, all) => (
* <>
* <span style={{ color: '#00eaff' }}>{key.toUpperCase()}</span>
* {i < all.length - 1 && <span style={{ opacity: 0.5 }}> + </span>}
* </>
* )}
* />
*
* @param {ShortcutLabelProps} props - Props for the ShortcutLabel component
* @param {string[]} props.keys - The list of keys to display.
* @param {Function} [props.renderKey] - Optional custom render function for full control over how each key appears.
*
* @returns {JSX.Element} Rendered shortcut label
*/
declare const ShortcutLabel: ({ keys, renderKey, style, ...props }: ShortcutLabelProps) => react_jsx_runtime.JSX.Element;
/**
* React hook to manage keyboard shortcuts using a shared instance of `ShortcutManager`.
* Automatically cleans up shortcuts registered by the component on unmount.
*
* @param {Object} config - Configuration object.
* @param {boolean} [config.logs=false] - Whether to enable debug logs in the console.
*
* @returns {Object} Object containing shortcut management methods.
*
* @example
* const {
* register,
* setScope,
* getCheatSheet,
* } = useKeybindy({ logs: true });
*
* useEffect(() => {
* register(['ctrl', 's'], () => save(), {
* scope: 'editor',
* data: { description: 'Save document' }
* });
* setScope('editor');
* }, []);
*/
declare function useKeybindy({ logs, onShortcutFired, }?: {
logs?: boolean;
onShortcutFired?: (info: Shortcut) => void;
}): {
register: (keys: Keys[] | Keys[][], handler: ShortcutHandler, options?: ShortcutOptions) => void;
unregister: (keys: Keys[], scope?: string) => void;
enable: (keys: Keys[], scope?: string) => void;
disable: (keys: Keys[], scope?: string) => void;
toggle: (keys: Keys[], scope?: string) => void;
setScope: (scope: string) => void;
getCheatSheet: (scope?: string) => {
keys: string[];
}[] | undefined;
destroy: () => void;
getScopeInfo: (scope?: string) => {
shortcuts: {
keys: string[];
id: string;
enabled: boolean;
data?: Record<string, string>;
}[];
isActive?: boolean;
} | Record<string, {
shortcuts: {
keys: string[];
id: string;
enabled: boolean;
data?: Record<string, string>;
}[];
isActive?: boolean;
}> | undefined;
getActiveScope: () => string | undefined;
popScope: () => void;
pushScope: (scope: string) => void;
resetScope: () => void;
getScopes: () => string[] | undefined;
isScopeActive: (scope: string) => boolean | undefined;
onTyping: (callback: (payload: {
key: string;
event: KeyboardEvent;
}) => void) => void;
enableAll: (scope?: string) => void;
clear: () => void;
disableAll: (scope?: string) => void;
manager: ShortcutManager;
};
export { Keybindy, ShortcutLabel, useKeybindy };