UNPKG

@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.

95 lines (92 loc) 3.02 kB
import { jsx, jsxs } from 'react/jsx-runtime'; import React from 'react'; /** * ... (rest of the description) ... * * @example * // Default usage * <ShortcutLabel keys={['ctrl', 's']} /> * * @example * // With multiple bindings * <ShortcutLabel keys={[['ctrl', 's'], ['meta', 's']]} /> * * @example * // With custom render prop * <ShortcutLabel * keys={['ctrl', 'shift', 'a']} * render={(keys) => { * // 'keys' here will be ['ctrl', 'shift', 'a'] * return keys.map((key) => ( * <span key={key} style={{ color: '#00eaff' }}> * {key.toUpperCase()} * </span> * )); * }} * /> * * @example * // With custom render prop for multiple bindings * <ShortcutLabel * keys={[['ctrl', 's'], ['meta', 's']]} * render={(bindings) => { * // 'bindings' here will be [['ctrl', 's'], ['meta', 's']] * return bindings.map((binding, bindingIndex) => ( * <React.Fragment key={bindingIndex}> * {binding.map((key, keyIndex) => ( * <span key={keyIndex} style={{ fontWeight: 'bold' }}> * {key} * </span> * ))} * {bindingIndex < bindings.length - 1 && ' or '} * </React.Fragment> * )); * }} * /> * * @param {ShortcutLabelProps} props - Props for the ShortcutLabel component * @param {string[] | string[][]} props.keys - The list of keys to display. * @param {Function} [props.render] - Optional custom render function for full control over how your keys are rendered. * * @returns {JSX.Element} Rendered shortcut label */ const ShortcutLabel = ({ keys, render, style, ...props }) => { const isMac = typeof navigator !== 'undefined' && /Mac/.test(navigator.userAgent); const defaultRenderKey = (key) => { switch (key.toLowerCase()) { case 'meta': return isMac ? '⌘' : 'Ctrl'; case 'ctrl': return 'Ctrl'; case 'shift': return '⇧'; case 'alt': return isMac ? '⌥' : 'Alt'; case 'enter': return '↵'; default: return key.toUpperCase(); } }; const renderBinding = (binding) => { if (render) { return render(binding); } return binding.map(key => defaultRenderKey(key)).join(' + '); }; const isNestedArray = Array.isArray(keys[0]); return (jsx("kbd", { style: { fontFamily: 'monospace', padding: '2.5px 5px', border: '1px solid #cccccc2f', backgroundColor: '#2e2e2e', borderRadius: '4px', userSelect: 'none', ...style, }, ...props, children: isNestedArray ? render ? renderBinding(keys) : keys.map((binding, index) => (jsxs(React.Fragment, { children: [renderBinding(binding), index < keys.length - 1 && ' / '] }, index))) : renderBinding(keys) })); }; export { ShortcutLabel };