@keybindy/react 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,232 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }'use client';
2
+
3
+ // src/Keybindy.tsx
4
+ var _react = require('react'); var _react2 = _interopRequireDefault(_react);
5
+
6
+ // src/useKeybindy.tsx
7
+
8
+ var _core = require('@keybindy/core'); var _core2 = _interopRequireDefault(_core);
9
+ var sharedInstance = null;
10
+ var useKeybindy = ({
11
+ logs = false,
12
+ onShortcutFired
13
+ } = {}) => {
14
+ const managerRef = _react2.default.useRef(null);
15
+ const registeredIds = _react2.default.useRef(/* @__PURE__ */ new Set());
16
+ if (!sharedInstance) {
17
+ sharedInstance = new (0, _core2.default)({ onShortcutFired, silent: !logs });
18
+ }
19
+ if (!managerRef.current) {
20
+ managerRef.current = sharedInstance;
21
+ }
22
+ const log = (...args) => {
23
+ if (logs) console.log("[Keybindy]", ...args);
24
+ };
25
+ const warn = (...args) => {
26
+ if (logs) console.warn("[Keybindy]", ...args);
27
+ };
28
+ const register = _react2.default.useCallback(
29
+ (keys, handler, options) => {
30
+ if (keys.length === 0) {
31
+ warn("No keys provided to register");
32
+ return;
33
+ }
34
+ const id = _optionalChain([options, 'optionalAccess', _ => _.data, 'optionalAccess', _2 => _2.id]);
35
+ if (id) registeredIds.current.add(id);
36
+ log("Registered:", _nullishCoalesce(id, () => ( keys)));
37
+ _optionalChain([managerRef, 'access', _3 => _3.current, 'optionalAccess', _4 => _4.register, 'call', _5 => _5(keys, handler, options)]);
38
+ },
39
+ []
40
+ );
41
+ const unregister = _react2.default.useCallback((keys, scope) => {
42
+ if (keys.length === 0) {
43
+ warn("No keys provided to unregister");
44
+ return;
45
+ }
46
+ _optionalChain([managerRef, 'access', _6 => _6.current, 'optionalAccess', _7 => _7.unregister, 'call', _8 => _8(keys, scope)]);
47
+ log("Unregistered:", keys);
48
+ }, []);
49
+ const enable = _react2.default.useCallback((keys, scope) => {
50
+ if (keys.length === 0) {
51
+ warn("No keys provided to enable");
52
+ return;
53
+ }
54
+ _optionalChain([managerRef, 'access', _9 => _9.current, 'optionalAccess', _10 => _10.enable, 'call', _11 => _11(keys, scope)]);
55
+ log("Enabled:", keys);
56
+ }, []);
57
+ const disable = _react2.default.useCallback((keys, scope) => {
58
+ if (keys.length === 0) {
59
+ warn("No keys provided to disable");
60
+ return;
61
+ }
62
+ _optionalChain([managerRef, 'access', _12 => _12.current, 'optionalAccess', _13 => _13.disable, 'call', _14 => _14(keys, scope)]);
63
+ log("Disabled:", keys);
64
+ }, []);
65
+ const toggle = _react2.default.useCallback((keys, scope) => {
66
+ if (keys.length === 0) {
67
+ warn("No keys provided to toggle");
68
+ return;
69
+ }
70
+ _optionalChain([managerRef, 'access', _15 => _15.current, 'optionalAccess', _16 => _16.toggle, 'call', _17 => _17(keys, scope)]);
71
+ log("Toggled:", keys);
72
+ }, []);
73
+ const getCheatSheet = _react2.default.useCallback((scope) => {
74
+ return _optionalChain([managerRef, 'access', _18 => _18.current, 'optionalAccess', _19 => _19.getCheatSheet, 'call', _20 => _20(scope)]);
75
+ }, []);
76
+ const getActiveScope = _react2.default.useCallback(() => {
77
+ return _nullishCoalesce(_optionalChain([managerRef, 'access', _21 => _21.current, 'optionalAccess', _22 => _22.getActiveScope, 'call', _23 => _23()]), () => ( ""));
78
+ }, []);
79
+ const disableAll = _react2.default.useCallback((scope) => {
80
+ _optionalChain([managerRef, 'access', _24 => _24.current, 'optionalAccess', _25 => _25.disableAll, 'call', _26 => _26(scope)]);
81
+ log(`Disabled all shortcuts${scope ? ` in scope "${scope}"` : ""}`);
82
+ }, []);
83
+ const enableAll = _react2.default.useCallback((scope) => {
84
+ _optionalChain([managerRef, 'access', _27 => _27.current, 'optionalAccess', _28 => _28.enableAll, 'call', _29 => _29(scope)]);
85
+ log(`Enabled all shortcuts${scope ? ` in scope "${scope}"` : ""}`);
86
+ }, []);
87
+ const setScope = _react2.default.useCallback((scope) => {
88
+ _optionalChain([managerRef, 'access', _30 => _30.current, 'optionalAccess', _31 => _31.setActiveScope, 'call', _32 => _32(scope)]);
89
+ log("Scope set to:", scope);
90
+ }, []);
91
+ const resetScope = _react2.default.useCallback(() => {
92
+ _optionalChain([managerRef, 'access', _33 => _33.current, 'optionalAccess', _34 => _34.resetScope, 'call', _35 => _35()]);
93
+ log("Reset scope");
94
+ }, []);
95
+ const getScopes = _react2.default.useCallback(() => {
96
+ return _nullishCoalesce(_optionalChain([managerRef, 'access', _36 => _36.current, 'optionalAccess', _37 => _37.getScopes, 'call', _38 => _38()]), () => ( []));
97
+ }, []);
98
+ const isScopeActive = _react2.default.useCallback((scope) => {
99
+ return _optionalChain([managerRef, 'access', _39 => _39.current, 'optionalAccess', _40 => _40.isScopeActive, 'call', _41 => _41(scope)]);
100
+ }, []);
101
+ const onTyping = _react2.default.useCallback(
102
+ (callback) => {
103
+ _optionalChain([managerRef, 'access', _42 => _42.current, 'optionalAccess', _43 => _43.onTyping, 'call', _44 => _44(callback)]);
104
+ },
105
+ []
106
+ );
107
+ const popScope = _react2.default.useCallback(() => {
108
+ _optionalChain([managerRef, 'access', _45 => _45.current, 'optionalAccess', _46 => _46.popScope, 'call', _47 => _47()]);
109
+ log("Popped scope, active scope is:", _optionalChain([managerRef, 'access', _48 => _48.current, 'optionalAccess', _49 => _49.getActiveScope, 'call', _50 => _50()]));
110
+ }, []);
111
+ const pushScope = _react2.default.useCallback((scope) => {
112
+ _optionalChain([managerRef, 'access', _51 => _51.current, 'optionalAccess', _52 => _52.pushScope, 'call', _53 => _53(scope)]);
113
+ log("Pushed scope:", scope);
114
+ }, []);
115
+ const getScopeInfo = _react2.default.useCallback((scope) => {
116
+ return _optionalChain([managerRef, 'access', _54 => _54.current, 'optionalAccess', _55 => _55.getScopesInfo, 'call', _56 => _56(scope)]);
117
+ }, []);
118
+ const destroy = () => {
119
+ _optionalChain([managerRef, 'access', _57 => _57.current, 'optionalAccess', _58 => _58.destroy, 'call', _59 => _59()]);
120
+ };
121
+ const clear = () => {
122
+ _optionalChain([managerRef, 'access', _60 => _60.current, 'optionalAccess', _61 => _61.clear, 'call', _62 => _62()]);
123
+ };
124
+ return {
125
+ register,
126
+ unregister,
127
+ enable,
128
+ disable,
129
+ toggle,
130
+ setScope,
131
+ getCheatSheet,
132
+ destroy,
133
+ getScopeInfo,
134
+ getActiveScope,
135
+ popScope,
136
+ pushScope,
137
+ resetScope,
138
+ getScopes,
139
+ isScopeActive,
140
+ onTyping,
141
+ enableAll,
142
+ clear,
143
+ disableAll,
144
+ manager: managerRef.current
145
+ };
146
+ };
147
+
148
+ // src/Keybindy.tsx
149
+ var _jsxruntime = require('react/jsx-runtime');
150
+ var Keybindy = ({
151
+ scope = "global",
152
+ shortcuts = [],
153
+ children,
154
+ disabled,
155
+ onShortcutFired,
156
+ logs = false
157
+ }) => {
158
+ const { register, unregister, manager, pushScope, popScope, getScopes, setScope } = useKeybindy({
159
+ onShortcutFired,
160
+ logs
161
+ });
162
+ const prevScope = _react2.default.useRef(null);
163
+ _react2.default.useEffect(() => {
164
+ prevScope.current = manager.getActiveScope();
165
+ if (!_optionalChain([getScopes, 'call', _63 => _63(), 'optionalAccess', _64 => _64.includes, 'call', _65 => _65(scope)])) {
166
+ pushScope(scope);
167
+ }
168
+ setScope(scope);
169
+ shortcuts.forEach(({ keys, handler, options }) => {
170
+ register(keys, handler, { ...options, scope });
171
+ });
172
+ if (disabled) {
173
+ manager.disableAll(scope);
174
+ }
175
+ return () => {
176
+ shortcuts.forEach(({ keys }) => {
177
+ if (Array.isArray(keys[0])) {
178
+ keys.forEach((key) => unregister(key, scope));
179
+ } else {
180
+ unregister(keys, scope);
181
+ }
182
+ });
183
+ popScope();
184
+ };
185
+ }, [scope, JSON.stringify(shortcuts)]);
186
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment, { children });
187
+ };
188
+
189
+ // src/ShortcutLabel.tsx
190
+
191
+
192
+ var ShortcutLabel = ({ keys, renderKey, style, ...props }) => {
193
+ const isMac = typeof navigator !== "undefined" && /Mac/.test(navigator.userAgent);
194
+ const defaultRenderKey = (key) => {
195
+ switch (key.toLowerCase()) {
196
+ case "meta":
197
+ return isMac ? "\u2318" : "Ctrl";
198
+ case "ctrl":
199
+ return "Ctrl";
200
+ case "shift":
201
+ return "\u21E7";
202
+ case "alt":
203
+ return isMac ? "\u2325" : "Alt";
204
+ case "enter":
205
+ return "\u21B5";
206
+ default:
207
+ return key.toUpperCase();
208
+ }
209
+ };
210
+ const rendered = renderKey ? keys.map((key, i) => /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react2.default.Fragment, { children: renderKey(key, i, keys) }, i)) : defaultRenderKey ? [keys.map((key) => defaultRenderKey(key)).join(" + ")] : [];
211
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
212
+ "kbd",
213
+ {
214
+ style: {
215
+ fontFamily: "monospace",
216
+ padding: "2.5px 5px",
217
+ border: "1px solid #cccccc2f",
218
+ backgroundColor: "#2e2e2e",
219
+ borderRadius: "4px",
220
+ userSelect: "none",
221
+ ...style
222
+ },
223
+ ...props,
224
+ children: rendered
225
+ }
226
+ );
227
+ };
228
+
229
+
230
+
231
+
232
+ exports.Keybindy = Keybindy; exports.ShortcutLabel = ShortcutLabel; exports.useKeybindy = useKeybindy;
package/package.json CHANGED
@@ -1,30 +1,29 @@
1
1
  {
2
2
  "name": "@keybindy/react",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "description": "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.",
5
5
  "author": {
6
6
  "name": "PRASSamin",
7
- "url": "https://github.com/prasssamin"
7
+ "url": "https://github.com/prassamin"
8
8
  },
9
9
  "repository": {
10
10
  "type": "git",
11
- "url": "git+https://github.com/keybindy/react.git"
11
+ "url": "git+https://github.com/keybindyjs/keybindy.git"
12
12
  },
13
- "homepage": "https://github.com/keybindy/react",
13
+ "homepage": "https://github.com/keybindyjs/keybindy",
14
14
  "bugs": {
15
- "url": "https://github.com/keybindy/react/issues"
15
+ "url": "https://github.com/keybindyjs/keybindy/issues"
16
16
  },
17
17
  "license": "MIT",
18
18
  "sideEffects": false,
19
19
  "type": "module",
20
- "main": "./dist/index.js",
21
- "module": "./dist/index.js",
22
- "types": "./dist/index.d.ts",
20
+ "main": "dist/index.cjs",
21
+ "module": "dist/index.mjs",
22
+ "types": "dist/index.d.ts",
23
23
  "exports": {
24
24
  ".": {
25
- "import": "./dist/index.js",
26
- "require": "./dist/index.js",
27
- "types": "./dist/index.d.ts"
25
+ "require": "./dist/index.cjs",
26
+ "import": "./dist/index.mjs"
28
27
  }
29
28
  },
30
29
  "files": [
@@ -45,28 +44,22 @@
45
44
  "react",
46
45
  "shortcut-engine"
47
46
  ],
48
- "scripts": {
49
- "format": "prettier --write \"src/**/*.{ts,tsx}\"",
50
- "publish": "npm publish --access public",
51
- "prebuild": "rm -rf dist",
52
- "build": "rollup -c",
53
- "dev": "rollup -c -w"
54
- },
55
47
  "devDependencies": {
56
- "@rollup/plugin-commonjs": "^28.0.3",
57
- "@rollup/plugin-node-resolve": "^16.0.1",
58
- "@rollup/plugin-typescript": "^12.1.2",
59
- "@types/bun": "latest",
60
48
  "@types/react": "^19.1.2",
61
- "prettier": "^3.5.3",
62
- "rollup-plugin-dts": "^6.2.1",
63
49
  "tslib": "^2.8.1"
64
50
  },
65
51
  "peerDependencies": {
66
52
  "typescript": "^5.0.0"
67
53
  },
68
54
  "dependencies": {
69
- "@keybindy/core": "^1.0.2",
70
- "react": "^19.1.0"
55
+ "react": "^19.1.0",
56
+ "@keybindy/core": "1.1.0"
57
+ },
58
+ "scripts": {
59
+ "format": "prettier --write \"src/**/*.{ts,tsx}\"",
60
+ "prebuild": "rm -rf dist",
61
+ "build": "tsup",
62
+ "dev": "tsup -w",
63
+ "test": "vitest"
71
64
  }
72
- }
65
+ }
@@ -1,87 +0,0 @@
1
- import React from 'react';
2
- import type { Keys, Shortcut as ShortcutType, ShortcutHandler, ShortcutOptions } from '@keybindy/core';
3
- /**
4
- * Represents a keyboard shortcut definition.
5
- */
6
- type ShortcutDefinition = {
7
- /**
8
- * The key combination(s) to listen for.
9
- * Can be a single array of keys or an array of key combinations.
10
- */
11
- keys: Keys[] | Keys[][];
12
- /**
13
- * Callback function to invoke when the shortcut is triggered.
14
- */
15
- handler: ShortcutHandler;
16
- /**
17
- * Optional configuration, including scope and other metadata.
18
- */
19
- options?: Omit<ShortcutOptions, 'scope'>;
20
- };
21
- /**
22
- * Props for the `<Keybindy />` component.
23
- */
24
- type KeybindyProps = {
25
- /**
26
- * The scope under which the shortcuts should be active.
27
- * This allows managing different contexts for shortcuts.
28
- */
29
- scope?: 'global' | string;
30
- /**
31
- * Array of shortcut definitions to register for this scope.
32
- */
33
- shortcuts?: ShortcutDefinition[];
34
- /**
35
- * Whether the shortcuts should be disabled for this scope.
36
- * Defaults to `false`.
37
- */
38
- disabled?: boolean;
39
- /**
40
- * Callback function that will be called when a shortcut is fired.
41
- * Receives the fired shortcut info as an argument.
42
- */
43
- onShortcutFired?: (info: ShortcutType) => void;
44
- /**
45
- * Whether to enable debug logs in the console.
46
- */
47
- logs?: boolean;
48
- /**
49
- * The content that will be rendered inside the Shortcut component.
50
- */
51
- children: React.ReactNode;
52
- };
53
- /**
54
- * `<Keybindy />` is a React component that registers keyboard shortcuts within a given scope. It allows
55
- * users to define custom shortcuts and their associated handlers, while managing scope-based shortcut behavior.
56
- * The component listens for keyboard events and triggers the registered handler when the corresponding keys are pressed.
57
- * It also provides an optional callback (`onShortcutFired`) to notify users when a shortcut is triggered.
58
- *
59
- * @component
60
- *
61
- * @example
62
- * // Basic usage
63
- * <Keybindy scope="global" shortcuts={[{ keys: ['ctrl', 's'], handler: saveDocument }]} >
64
- * <div>Content with shortcuts</div>
65
- * </Keybindy>
66
- *
67
- * @example
68
- * // With custom callback for onShortcutFired
69
- * <Keybindy
70
- * scope="editor"
71
- * shortcuts={[{ keys: ['ctrl', 'e'], handler: editDocument }]}
72
- * onShortcutFired={(info) => console.log('Shortcut fired:', info)}
73
- * >
74
- * <div>Editor with shortcuts</div>
75
- * </Keybindy>
76
- *
77
- * @param {ShortcutProps} props - Props for the Shortcut component.
78
- * @param {string} props.scope - The scope under which the shortcuts should be active.
79
- * @param {ShortcutDefinition[]} [props.shortcuts] - An array of shortcut definitions, each containing keys, handler, and options.
80
- * @param {boolean} [props.disabled=false] - Whether the shortcuts should be disabled for this scope.
81
- * @param {(info: Shortcut) => void} [props.onShortcutFired] - Optional callback triggered when a shortcut is fired, providing the shortcut info.
82
- * @param {React.ReactNode} props.children - The children to be rendered inside the component, which can contain any JSX elements.
83
- *
84
- * @returns {JSX.Element} The rendered component with registered shortcuts within the provided scope.
85
- */
86
- export declare const Keybindy: React.FC<KeybindyProps>;
87
- export {};
package/dist/Keybindy.js DELETED
@@ -1,74 +0,0 @@
1
- import { jsx, Fragment } from 'react/jsx-runtime';
2
- import React from 'react';
3
- import { useKeybindy } from './useKeybindy.js';
4
-
5
- /**
6
- * `<Keybindy />` is a React component that registers keyboard shortcuts within a given scope. It allows
7
- * users to define custom shortcuts and their associated handlers, while managing scope-based shortcut behavior.
8
- * The component listens for keyboard events and triggers the registered handler when the corresponding keys are pressed.
9
- * It also provides an optional callback (`onShortcutFired`) to notify users when a shortcut is triggered.
10
- *
11
- * @component
12
- *
13
- * @example
14
- * // Basic usage
15
- * <Keybindy scope="global" shortcuts={[{ keys: ['ctrl', 's'], handler: saveDocument }]} >
16
- * <div>Content with shortcuts</div>
17
- * </Keybindy>
18
- *
19
- * @example
20
- * // With custom callback for onShortcutFired
21
- * <Keybindy
22
- * scope="editor"
23
- * shortcuts={[{ keys: ['ctrl', 'e'], handler: editDocument }]}
24
- * onShortcutFired={(info) => console.log('Shortcut fired:', info)}
25
- * >
26
- * <div>Editor with shortcuts</div>
27
- * </Keybindy>
28
- *
29
- * @param {ShortcutProps} props - Props for the Shortcut component.
30
- * @param {string} props.scope - The scope under which the shortcuts should be active.
31
- * @param {ShortcutDefinition[]} [props.shortcuts] - An array of shortcut definitions, each containing keys, handler, and options.
32
- * @param {boolean} [props.disabled=false] - Whether the shortcuts should be disabled for this scope.
33
- * @param {(info: Shortcut) => void} [props.onShortcutFired] - Optional callback triggered when a shortcut is fired, providing the shortcut info.
34
- * @param {React.ReactNode} props.children - The children to be rendered inside the component, which can contain any JSX elements.
35
- *
36
- * @returns {JSX.Element} The rendered component with registered shortcuts within the provided scope.
37
- */
38
- const Keybindy = ({ scope = 'global', shortcuts = [], children, disabled, onShortcutFired, logs = false, }) => {
39
- const { register, unregister, manager, pushScope, popScope, getScopes, setScope } = useKeybindy({
40
- onShortcutFired,
41
- logs,
42
- });
43
- const prevScope = React.useRef(null);
44
- React.useEffect(() => {
45
- prevScope.current = manager.getActiveScope();
46
- // Add scope if doesn't exist
47
- if (!getScopes()?.includes(scope)) {
48
- pushScope(scope);
49
- }
50
- // Set this scope as active
51
- setScope(scope);
52
- // Register all shortcuts for this scope
53
- shortcuts.forEach(({ keys, handler, options }) => {
54
- register(keys, handler, { ...options, scope });
55
- });
56
- if (disabled) {
57
- manager.disableAll(scope);
58
- }
59
- return () => {
60
- shortcuts.forEach(({ keys }) => {
61
- if (Array.isArray(keys[0])) {
62
- keys.forEach(key => unregister(key, scope));
63
- }
64
- else {
65
- unregister(keys, scope);
66
- }
67
- });
68
- popScope();
69
- };
70
- }, [scope, JSON.stringify(shortcuts)]);
71
- return jsx(Fragment, { children: children });
72
- };
73
-
74
- export { Keybindy };
@@ -1,57 +0,0 @@
1
- import type { Keys } from '@keybindy/core';
2
- import React from 'react';
3
- interface ShortcutLabelProps extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> {
4
- /**
5
- * Array of keys to display
6
- */
7
- keys: Omit<Keys, 'Ctrl (Left)' | 'Ctrl (Right)' | 'Shift (Left)' | 'Shift (Right)' | 'Alt (Left)' | 'Alt (Right)' | 'Meta (Left)' | 'Meta (Right)'>[];
8
- /**
9
- * Custom render function for each key
10
- */
11
- renderKey?: (
12
- /**
13
- * The key to render
14
- */
15
- key: string,
16
- /**
17
- * The index of the key in the array
18
- */
19
- index: number,
20
- /**
21
- * All keys in the array
22
- */
23
- allKeys: string[]) => React.ReactNode;
24
- }
25
- /**
26
- * `<ShortcutLabel />` is a utility React component that visually renders a keyboard shortcut label.
27
- *
28
- * It accepts an array of keys (e.g. `["Ctrl", "S"]`) and renders a styled label using platform-aware
29
- * symbols (⌘ for Mac, Ctrl for others). Users can also provide a custom render function to override
30
- * the default display logic for advanced layouts or custom themes.
31
- *
32
- * @component
33
- *
34
- * @example
35
- * // Default usage
36
- * <ShortcutLabel keys={['ctrl', 's']} />
37
- *
38
- * @example
39
- * // With custom renderKey
40
- * <ShortcutLabel
41
- * keys={['ctrl', 'alt', 'delete']}
42
- * renderKey={(key, i, all) => (
43
- * <>
44
- * <span style={{ color: '#00eaff' }}>{key.toUpperCase()}</span>
45
- * {i < all.length - 1 && <span style={{ opacity: 0.5 }}> + </span>}
46
- * </>
47
- * )}
48
- * />
49
- *
50
- * @param {ShortcutLabelProps} props - Props for the ShortcutLabel component
51
- * @param {string[]} props.keys - The list of keys to display.
52
- * @param {Function} [props.renderKey] - Optional custom render function for full control over how each key appears.
53
- *
54
- * @returns {JSX.Element} Rendered shortcut label
55
- */
56
- export declare const ShortcutLabel: ({ keys, renderKey, style, ...props }: ShortcutLabelProps) => import("react/jsx-runtime").JSX.Element;
57
- export {};
@@ -1,69 +0,0 @@
1
- import { jsx } from 'react/jsx-runtime';
2
- import React from 'react';
3
-
4
- /**
5
- * `<ShortcutLabel />` is a utility React component that visually renders a keyboard shortcut label.
6
- *
7
- * It accepts an array of keys (e.g. `["Ctrl", "S"]`) and renders a styled label using platform-aware
8
- * symbols (⌘ for Mac, Ctrl for others). Users can also provide a custom render function to override
9
- * the default display logic for advanced layouts or custom themes.
10
- *
11
- * @component
12
- *
13
- * @example
14
- * // Default usage
15
- * <ShortcutLabel keys={['ctrl', 's']} />
16
- *
17
- * @example
18
- * // With custom renderKey
19
- * <ShortcutLabel
20
- * keys={['ctrl', 'alt', 'delete']}
21
- * renderKey={(key, i, all) => (
22
- * <>
23
- * <span style={{ color: '#00eaff' }}>{key.toUpperCase()}</span>
24
- * {i < all.length - 1 && <span style={{ opacity: 0.5 }}> + </span>}
25
- * </>
26
- * )}
27
- * />
28
- *
29
- * @param {ShortcutLabelProps} props - Props for the ShortcutLabel component
30
- * @param {string[]} props.keys - The list of keys to display.
31
- * @param {Function} [props.renderKey] - Optional custom render function for full control over how each key appears.
32
- *
33
- * @returns {JSX.Element} Rendered shortcut label
34
- */
35
- const ShortcutLabel = ({ keys, renderKey, style, ...props }) => {
36
- const isMac = typeof navigator !== 'undefined' && /Mac/.test(navigator.userAgent);
37
- const defaultRenderKey = (key) => {
38
- switch (key.toLowerCase()) {
39
- case 'meta':
40
- return isMac ? '⌘' : 'Ctrl';
41
- case 'ctrl':
42
- return 'Ctrl';
43
- case 'shift':
44
- return '⇧';
45
- case 'alt':
46
- return isMac ? '⌥' : 'Alt';
47
- case 'enter':
48
- return '↵';
49
- default:
50
- return key.toUpperCase();
51
- }
52
- };
53
- const rendered = renderKey
54
- ? keys.map((key, i) => (jsx(React.Fragment, { children: renderKey(key, i, keys) }, i)))
55
- : defaultRenderKey
56
- ? [keys.map(key => defaultRenderKey(key)).join(' + ')]
57
- : [];
58
- return (jsx("kbd", { style: {
59
- fontFamily: 'monospace',
60
- padding: '2.5px 5px',
61
- border: '1px solid #cccccc2f',
62
- backgroundColor: '#2e2e2e',
63
- borderRadius: '4px',
64
- userSelect: 'none',
65
- ...style,
66
- }, ...props, children: rendered }));
67
- };
68
-
69
- export { ShortcutLabel };
package/dist/index.d.ts DELETED
@@ -1,202 +0,0 @@
1
- import React from 'react';
2
- import ShortcutManager, { Keys, ShortcutHandler, ShortcutOptions, Shortcut } from '@keybindy/core';
3
- export { KeyBinding, Keys, Shortcut, ShortcutHandler, ShortcutOptions } from '@keybindy/core';
4
- import * as react_jsx_runtime from 'react/jsx-runtime';
5
-
6
- /**
7
- * Represents a keyboard shortcut definition.
8
- */
9
- type ShortcutDefinition = {
10
- /**
11
- * The key combination(s) to listen for.
12
- * Can be a single array of keys or an array of key combinations.
13
- */
14
- keys: Keys[] | Keys[][];
15
- /**
16
- * Callback function to invoke when the shortcut is triggered.
17
- */
18
- handler: ShortcutHandler;
19
- /**
20
- * Optional configuration, including scope and other metadata.
21
- */
22
- options?: Omit<ShortcutOptions, 'scope'>;
23
- };
24
- /**
25
- * Props for the `<Keybindy />` component.
26
- */
27
- type KeybindyProps = {
28
- /**
29
- * The scope under which the shortcuts should be active.
30
- * This allows managing different contexts for shortcuts.
31
- */
32
- scope?: 'global' | string;
33
- /**
34
- * Array of shortcut definitions to register for this scope.
35
- */
36
- shortcuts?: ShortcutDefinition[];
37
- /**
38
- * Whether the shortcuts should be disabled for this scope.
39
- * Defaults to `false`.
40
- */
41
- disabled?: boolean;
42
- /**
43
- * Callback function that will be called when a shortcut is fired.
44
- * Receives the fired shortcut info as an argument.
45
- */
46
- onShortcutFired?: (info: Shortcut) => void;
47
- /**
48
- * Whether to enable debug logs in the console.
49
- */
50
- logs?: boolean;
51
- /**
52
- * The content that will be rendered inside the Shortcut component.
53
- */
54
- children: React.ReactNode;
55
- };
56
- /**
57
- * `<Keybindy />` is a React component that registers keyboard shortcuts within a given scope. It allows
58
- * users to define custom shortcuts and their associated handlers, while managing scope-based shortcut behavior.
59
- * The component listens for keyboard events and triggers the registered handler when the corresponding keys are pressed.
60
- * It also provides an optional callback (`onShortcutFired`) to notify users when a shortcut is triggered.
61
- *
62
- * @component
63
- *
64
- * @example
65
- * // Basic usage
66
- * <Keybindy scope="global" shortcuts={[{ keys: ['ctrl', 's'], handler: saveDocument }]} >
67
- * <div>Content with shortcuts</div>
68
- * </Keybindy>
69
- *
70
- * @example
71
- * // With custom callback for onShortcutFired
72
- * <Keybindy
73
- * scope="editor"
74
- * shortcuts={[{ keys: ['ctrl', 'e'], handler: editDocument }]}
75
- * onShortcutFired={(info) => console.log('Shortcut fired:', info)}
76
- * >
77
- * <div>Editor with shortcuts</div>
78
- * </Keybindy>
79
- *
80
- * @param {ShortcutProps} props - Props for the Shortcut component.
81
- * @param {string} props.scope - The scope under which the shortcuts should be active.
82
- * @param {ShortcutDefinition[]} [props.shortcuts] - An array of shortcut definitions, each containing keys, handler, and options.
83
- * @param {boolean} [props.disabled=false] - Whether the shortcuts should be disabled for this scope.
84
- * @param {(info: Shortcut) => void} [props.onShortcutFired] - Optional callback triggered when a shortcut is fired, providing the shortcut info.
85
- * @param {React.ReactNode} props.children - The children to be rendered inside the component, which can contain any JSX elements.
86
- *
87
- * @returns {JSX.Element} The rendered component with registered shortcuts within the provided scope.
88
- */
89
- declare const Keybindy: React.FC<KeybindyProps>;
90
-
91
- interface ShortcutLabelProps extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> {
92
- /**
93
- * Array of keys to display
94
- */
95
- keys: Omit<Keys, 'Ctrl (Left)' | 'Ctrl (Right)' | 'Shift (Left)' | 'Shift (Right)' | 'Alt (Left)' | 'Alt (Right)' | 'Meta (Left)' | 'Meta (Right)'>[];
96
- /**
97
- * Custom render function for each key
98
- */
99
- renderKey?: (
100
- /**
101
- * The key to render
102
- */
103
- key: string,
104
- /**
105
- * The index of the key in the array
106
- */
107
- index: number,
108
- /**
109
- * All keys in the array
110
- */
111
- allKeys: string[]) => React.ReactNode;
112
- }
113
- /**
114
- * `<ShortcutLabel />` is a utility React component that visually renders a keyboard shortcut label.
115
- *
116
- * It accepts an array of keys (e.g. `["Ctrl", "S"]`) and renders a styled label using platform-aware
117
- * symbols (⌘ for Mac, Ctrl for others). Users can also provide a custom render function to override
118
- * the default display logic for advanced layouts or custom themes.
119
- *
120
- * @component
121
- *
122
- * @example
123
- * // Default usage
124
- * <ShortcutLabel keys={['ctrl', 's']} />
125
- *
126
- * @example
127
- * // With custom renderKey
128
- * <ShortcutLabel
129
- * keys={['ctrl', 'alt', 'delete']}
130
- * renderKey={(key, i, all) => (
131
- * <>
132
- * <span style={{ color: '#00eaff' }}>{key.toUpperCase()}</span>
133
- * {i < all.length - 1 && <span style={{ opacity: 0.5 }}> + </span>}
134
- * </>
135
- * )}
136
- * />
137
- *
138
- * @param {ShortcutLabelProps} props - Props for the ShortcutLabel component
139
- * @param {string[]} props.keys - The list of keys to display.
140
- * @param {Function} [props.renderKey] - Optional custom render function for full control over how each key appears.
141
- *
142
- * @returns {JSX.Element} Rendered shortcut label
143
- */
144
- declare const ShortcutLabel: ({ keys, renderKey, style, ...props }: ShortcutLabelProps) => react_jsx_runtime.JSX.Element;
145
-
146
- type UseKeybindyReturn = {
147
- register: (keys: Keys[] | Keys[][], handler: ShortcutHandler, options?: ShortcutOptions) => void;
148
- unregister: (keys: Keys[], scope?: string) => void;
149
- enable: (keys: Keys[], scope?: string) => void;
150
- disable: (keys: Keys[], scope?: string) => void;
151
- toggle: (keys: Keys[], scope?: string) => void;
152
- setScope: (scope: string) => void;
153
- getCheatSheet: (scope?: string) => {
154
- keys: string[];
155
- }[] | undefined;
156
- destroy: () => void;
157
- getScopeInfo: (scope?: string) => any;
158
- getActiveScope: () => string;
159
- popScope: () => void;
160
- pushScope: (scope: string) => void;
161
- resetScope: () => void;
162
- getScopes: () => string[];
163
- isScopeActive: (scope: string) => boolean | undefined;
164
- onTyping: (callback: (payload: {
165
- key: string;
166
- event: KeyboardEvent;
167
- }) => void) => void;
168
- enableAll: (scope?: string) => void;
169
- clear: () => void;
170
- disableAll: (scope?: string) => void;
171
- manager: ShortcutManager;
172
- };
173
- /**
174
- * React hook to manage keyboard shortcuts using a shared instance of `ShortcutManager`.
175
- * Automatically cleans up shortcuts registered by the component on unmount.
176
- *
177
- * @param {Object} config - Configuration object.
178
- * @param {boolean} [config.logs=false] - Whether to enable debug logs in the console.
179
- *
180
- * @returns {Object} Object containing shortcut management methods.
181
- *
182
- * @example
183
- * const {
184
- * register,
185
- * setScope,
186
- * getCheatSheet,
187
- * } = useKeybindy({ logs: true });
188
- *
189
- * useEffect(() => {
190
- * register(['ctrl', 's'], () => save(), {
191
- * scope: 'editor',
192
- * data: { description: 'Save document' }
193
- * });
194
- * setScope('editor');
195
- * }, []);
196
- */
197
- declare const useKeybindy: ({ logs, onShortcutFired, }?: {
198
- logs?: boolean;
199
- onShortcutFired?: (info: Shortcut) => void;
200
- }) => UseKeybindyReturn;
201
-
202
- export { Keybindy, ShortcutLabel, useKeybindy };
package/dist/index.js DELETED
@@ -1,3 +0,0 @@
1
- export { Keybindy } from './Keybindy.js';
2
- export { ShortcutLabel } from './ShortcutLabel.js';
3
- export { useKeybindy } from './useKeybindy.js';
@@ -1,58 +0,0 @@
1
- import ShortcutManager from '@keybindy/core';
2
- import type { Keys, Shortcut, ShortcutHandler, ShortcutOptions } from '@keybindy/core';
3
- type UseKeybindyReturn = {
4
- register: (keys: Keys[] | Keys[][], handler: ShortcutHandler, options?: ShortcutOptions) => void;
5
- unregister: (keys: Keys[], scope?: string) => void;
6
- enable: (keys: Keys[], scope?: string) => void;
7
- disable: (keys: Keys[], scope?: string) => void;
8
- toggle: (keys: Keys[], scope?: string) => void;
9
- setScope: (scope: string) => void;
10
- getCheatSheet: (scope?: string) => {
11
- keys: string[];
12
- }[] | undefined;
13
- destroy: () => void;
14
- getScopeInfo: (scope?: string) => any;
15
- getActiveScope: () => string;
16
- popScope: () => void;
17
- pushScope: (scope: string) => void;
18
- resetScope: () => void;
19
- getScopes: () => string[];
20
- isScopeActive: (scope: string) => boolean | undefined;
21
- onTyping: (callback: (payload: {
22
- key: string;
23
- event: KeyboardEvent;
24
- }) => void) => void;
25
- enableAll: (scope?: string) => void;
26
- clear: () => void;
27
- disableAll: (scope?: string) => void;
28
- manager: ShortcutManager;
29
- };
30
- /**
31
- * React hook to manage keyboard shortcuts using a shared instance of `ShortcutManager`.
32
- * Automatically cleans up shortcuts registered by the component on unmount.
33
- *
34
- * @param {Object} config - Configuration object.
35
- * @param {boolean} [config.logs=false] - Whether to enable debug logs in the console.
36
- *
37
- * @returns {Object} Object containing shortcut management methods.
38
- *
39
- * @example
40
- * const {
41
- * register,
42
- * setScope,
43
- * getCheatSheet,
44
- * } = useKeybindy({ logs: true });
45
- *
46
- * useEffect(() => {
47
- * register(['ctrl', 's'], () => save(), {
48
- * scope: 'editor',
49
- * data: { description: 'Save document' }
50
- * });
51
- * setScope('editor');
52
- * }, []);
53
- */
54
- export declare const useKeybindy: ({ logs, onShortcutFired, }?: {
55
- logs?: boolean;
56
- onShortcutFired?: (info: Shortcut) => void;
57
- }) => UseKeybindyReturn;
58
- export {};
@@ -1,253 +0,0 @@
1
- import React from 'react';
2
- import ShortcutManager from '@keybindy/core';
3
-
4
- let sharedInstance = null;
5
- /**
6
- * React hook to manage keyboard shortcuts using a shared instance of `ShortcutManager`.
7
- * Automatically cleans up shortcuts registered by the component on unmount.
8
- *
9
- * @param {Object} config - Configuration object.
10
- * @param {boolean} [config.logs=false] - Whether to enable debug logs in the console.
11
- *
12
- * @returns {Object} Object containing shortcut management methods.
13
- *
14
- * @example
15
- * const {
16
- * register,
17
- * setScope,
18
- * getCheatSheet,
19
- * } = useKeybindy({ logs: true });
20
- *
21
- * useEffect(() => {
22
- * register(['ctrl', 's'], () => save(), {
23
- * scope: 'editor',
24
- * data: { description: 'Save document' }
25
- * });
26
- * setScope('editor');
27
- * }, []);
28
- */
29
- const useKeybindy = ({ logs = false, onShortcutFired, } = {}) => {
30
- const managerRef = React.useRef(null);
31
- const registeredIds = React.useRef(new Set());
32
- if (!sharedInstance) {
33
- sharedInstance = new ShortcutManager({ onShortcutFired, silent: !logs });
34
- }
35
- if (!managerRef.current) {
36
- managerRef.current = sharedInstance;
37
- managerRef.current.start();
38
- }
39
- const log = (...args) => {
40
- if (logs)
41
- console.log('[Keybindy]', ...args);
42
- };
43
- const warn = (...args) => {
44
- if (logs)
45
- console.warn('[Keybindy]', ...args);
46
- };
47
- /**
48
- * Registers a new keyboard shortcut.
49
- *
50
- * @param {Keys[] | Keys[][]} keys - Key combination(s) to listen for.
51
- * @param {ShortcutHandler} handler - Callback function to invoke when shortcut is triggered.
52
- * @param {ShortcutOptions} [options] - Optional configuration, including scope and metadata.
53
- */
54
- const register = React.useCallback((keys, handler, options) => {
55
- if (keys.length === 0) {
56
- warn('No keys provided to register');
57
- return;
58
- }
59
- const id = options?.data?.id;
60
- if (id)
61
- registeredIds.current.add(id);
62
- log('Registered:', id ?? keys);
63
- managerRef.current?.register(keys, handler, options);
64
- }, []);
65
- /**
66
- * Unregisters a previously registered keyboard shortcut.
67
- *
68
- * @param {Keys[]} keys - Key combination to unregister.
69
- * @param {string} [scope] - Optional scope for more targeted unregistration.
70
- */
71
- const unregister = React.useCallback((keys, scope) => {
72
- if (keys.length === 0) {
73
- warn('No keys provided to unregister');
74
- return;
75
- }
76
- managerRef.current?.unregister(keys, scope);
77
- log('Unregistered:', keys);
78
- }, []);
79
- /**
80
- * Enables a previously disabled shortcut.
81
- *
82
- * @param {Keys[]} keys - Key combination to enable.
83
- * @param {string} [scope] - Optional scope to target a specific set.
84
- */
85
- const enable = React.useCallback((keys, scope) => {
86
- if (keys.length === 0) {
87
- warn('No keys provided to enable');
88
- return;
89
- }
90
- managerRef.current?.enable(keys, scope);
91
- log('Enabled:', keys);
92
- }, []);
93
- /**
94
- * Disables a shortcut so it no longer triggers its handler.
95
- *
96
- * @param {Keys[]} keys - Key combination to disable.
97
- * @param {string} [scope] - Optional scope to target a specific set.
98
- */
99
- const disable = React.useCallback((keys, scope) => {
100
- if (keys.length === 0) {
101
- warn('No keys provided to disable');
102
- return;
103
- }
104
- managerRef.current?.disable(keys, scope);
105
- log('Disabled:', keys);
106
- }, []);
107
- /**
108
- * Toggles a shortcut between enabled and disabled.
109
- *
110
- * @param {Keys[]} keys - Key combination to toggle.
111
- * @param {string} [scope] - Optional scope to target a specific set.
112
- */
113
- const toggle = React.useCallback((keys, scope) => {
114
- if (keys.length === 0) {
115
- warn('No keys provided to toggle');
116
- return;
117
- }
118
- managerRef.current?.toggle(keys, scope);
119
- log('Toggled:', keys);
120
- }, []);
121
- /**
122
- * Returns a list of shortcuts registered in a given scope.
123
- *
124
- * @param {string} [scope] - The scope to query. Defaults to the active scope.
125
- * @returns {Array} List of shortcut definitions.
126
- */
127
- const getCheatSheet = React.useCallback((scope) => {
128
- return managerRef.current?.getCheatSheet(scope);
129
- }, []);
130
- /**
131
- * Returns the currently active scope.
132
- * @returns {string} The active scope.
133
- */
134
- const getActiveScope = React.useCallback(() => {
135
- return managerRef.current?.getActiveScope() ?? '';
136
- }, []);
137
- /**
138
- * Disables all shortcuts in the specified scope or all scopes if no scope is provided.
139
- * @param scope - The scope to disable shortcuts in.
140
- */
141
- const disableAll = React.useCallback((scope) => {
142
- managerRef.current?.disableAll(scope);
143
- log(`Disabled all shortcuts${scope ? ` in scope "${scope}"` : ''}`);
144
- }, []);
145
- /**
146
- * Enables all shortcuts in the specified scope or all scopes if no scope is provided.
147
- * @param scope - The scope to enable shortcuts in.
148
- */
149
- const enableAll = React.useCallback((scope) => {
150
- managerRef.current?.enableAll(scope);
151
- log(`Enabled all shortcuts${scope ? ` in scope "${scope}"` : ''}`);
152
- }, []);
153
- /**
154
- * Sets the currently active shortcut scope.
155
- *
156
- * @param {string} scope - The scope name to set as active.
157
- */
158
- const setScope = React.useCallback((scope) => {
159
- managerRef.current?.setActiveScope(scope);
160
- log('Scope set to:', scope);
161
- }, []);
162
- /**
163
- * Resets the scope stack to the default state.
164
- */
165
- const resetScope = React.useCallback(() => {
166
- managerRef.current?.resetScope();
167
- log('Reset scope');
168
- }, []);
169
- /**
170
- * Returns all scopes in the stack.
171
- * @returns An array of scopes.
172
- */
173
- const getScopes = React.useCallback(() => {
174
- return managerRef.current?.getScopes() ?? [];
175
- }, []);
176
- /**
177
- * Checks if the given scope is active.
178
- * @param scope - The scope to check.
179
- * @returns `true` if the scope is active, `false` otherwise.
180
- */
181
- const isScopeActive = React.useCallback((scope) => {
182
- return managerRef.current?.isScopeActive(scope);
183
- }, []);
184
- /**
185
- * Registers a callback to be called when a key is typed.
186
- * @param callback - The callback function to be called.
187
- */
188
- const onTyping = React.useCallback((callback) => {
189
- managerRef.current?.onTyping(callback);
190
- }, []);
191
- /**
192
- * Pops the last scope from the scope stack.
193
- */
194
- const popScope = React.useCallback(() => {
195
- managerRef.current?.popScope();
196
- log('Popped scope, active scope is:', managerRef.current?.getActiveScope());
197
- }, []);
198
- /**
199
- * Pushes a new scope onto the scope stack.
200
- * @param scope - The scope to push.
201
- */
202
- const pushScope = React.useCallback((scope) => {
203
- managerRef.current?.pushScope(scope);
204
- log('Pushed scope:', scope);
205
- }, []);
206
- /**
207
- * Returns internal information about the registered scopes and shortcuts.
208
- *
209
- * @param {string} [scope] - Optional scope to filter results.
210
- * @returns {Object} Scope information.
211
- */
212
- const getScopeInfo = React.useCallback((scope) => {
213
- return managerRef.current?.getScopesInfo(scope);
214
- }, []);
215
- /**
216
- * Destroys the instance of `ShortcutManager`.
217
- * This should be called explicitly when you no longer need the manager.
218
- */
219
- const destroy = () => {
220
- managerRef.current?.destroy();
221
- };
222
- /**
223
- * Clears the internal state, removing all pressed keys and event listeners.
224
- * This does not unregister shortcuts.
225
- */
226
- const clear = () => {
227
- managerRef.current?.clear();
228
- };
229
- return {
230
- register,
231
- unregister,
232
- enable,
233
- disable,
234
- toggle,
235
- setScope,
236
- getCheatSheet,
237
- destroy,
238
- getScopeInfo,
239
- getActiveScope,
240
- popScope,
241
- pushScope,
242
- resetScope,
243
- getScopes,
244
- isScopeActive,
245
- onTyping,
246
- enableAll,
247
- clear,
248
- disableAll,
249
- manager: managerRef.current,
250
- };
251
- };
252
-
253
- export { useKeybindy };