@keybindy/react 1.1.2 → 1.1.3

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.
@@ -0,0 +1,80 @@
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
+ if (!manager) {
46
+ return;
47
+ }
48
+ prevScope.current = manager.getActiveScope() ?? 'global';
49
+ // Add scope if doesn't exist
50
+ if (!getScopes()?.includes(scope)) {
51
+ pushScope(scope);
52
+ }
53
+ // Set this scope as active
54
+ setScope(scope);
55
+ // Register all shortcuts for this scope
56
+ shortcuts.forEach(({ keys, handler, options }) => {
57
+ register(keys, handler, { ...options, scope });
58
+ });
59
+ if (disabled) {
60
+ manager.disableAll(scope);
61
+ }
62
+ else {
63
+ manager.enableAll(scope);
64
+ }
65
+ return () => {
66
+ shortcuts.forEach(({ keys }) => {
67
+ if (Array.isArray(keys[0])) {
68
+ keys.forEach(key => unregister(key, scope));
69
+ }
70
+ else {
71
+ unregister(keys, scope);
72
+ }
73
+ });
74
+ popScope();
75
+ };
76
+ }, [scope, shortcuts, manager, disabled]);
77
+ return jsx(Fragment, { children: children });
78
+ };
79
+
80
+ export { Keybindy };
@@ -0,0 +1,69 @@
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.js ADDED
@@ -0,0 +1,3 @@
1
+ export { Keybindy } from './Keybindy.js';
2
+ export { ShortcutLabel } from './ShortcutLabel.js';
3
+ export { useKeybindy } from './useKeybindy.js';
@@ -0,0 +1,163 @@
1
+ import React from 'react';
2
+ import ShortcutManager from '@keybindy/core';
3
+
4
+ let sharedInstance = null;
5
+ const getSharedInstance = (options) => {
6
+ if (typeof window === 'undefined') {
7
+ return null;
8
+ }
9
+ if (!sharedInstance) {
10
+ sharedInstance = new ShortcutManager(options);
11
+ }
12
+ return sharedInstance;
13
+ };
14
+ /**
15
+ * React hook to manage keyboard shortcuts using a shared instance of `ShortcutManager`.
16
+ * This hook is safe for server-side rendering (SSR) and will only initialize the manager on the client.
17
+ *
18
+ * @param {Object} config - Configuration object.
19
+ * @param {boolean} [config.logs=false] - Whether to enable debug logs in the console.
20
+ * @param {(info: Shortcut) => void} [config.onShortcutFired] - Callback for when a shortcut is fired.
21
+ *
22
+ * @returns {Object} Object containing shortcut management methods and the manager instance (null on server).
23
+ */
24
+ const useKeybindy = ({ logs = false, onShortcutFired, } = {}) => {
25
+ const [manager, setManager] = React.useState(null);
26
+ React.useEffect(() => {
27
+ if (!manager) {
28
+ const instance = getSharedInstance({ onShortcutFired, silent: !logs });
29
+ setManager(instance);
30
+ }
31
+ }, []);
32
+ const log = (...args) => {
33
+ if (logs)
34
+ console.log('[Keybindy]', ...args);
35
+ };
36
+ const warn = (...args) => {
37
+ if (logs)
38
+ console.warn('[Keybindy]', ...args);
39
+ };
40
+ const register = React.useCallback((keys, handler, options) => {
41
+ if (!manager)
42
+ return;
43
+ if (keys.length === 0) {
44
+ warn('No keys provided to register');
45
+ return;
46
+ }
47
+ const id = options?.data?.id;
48
+ log('Registered:', id ?? keys);
49
+ manager.register(keys, handler, options);
50
+ }, [manager]);
51
+ const unregister = React.useCallback((keys, scope) => {
52
+ if (!manager)
53
+ return;
54
+ if (keys.length === 0) {
55
+ warn('No keys provided to unregister');
56
+ return;
57
+ }
58
+ manager.unregister(keys, scope);
59
+ log('Unregistered:', keys);
60
+ }, [manager]);
61
+ const enable = React.useCallback((keys, scope) => {
62
+ if (!manager)
63
+ return;
64
+ if (keys.length === 0) {
65
+ warn('No keys provided to enable');
66
+ return;
67
+ }
68
+ manager.enable(keys, scope);
69
+ log('Enabled:', keys);
70
+ }, [manager]);
71
+ const disable = React.useCallback((keys, scope) => {
72
+ if (!manager)
73
+ return;
74
+ if (keys.length === 0) {
75
+ warn('No keys provided to disable');
76
+ return;
77
+ }
78
+ manager.disable(keys, scope);
79
+ log('Disabled:', keys);
80
+ }, [manager]);
81
+ const toggle = React.useCallback((keys, scope) => {
82
+ if (!manager)
83
+ return;
84
+ if (keys.length === 0) {
85
+ warn('No keys provided to toggle');
86
+ return;
87
+ }
88
+ manager.toggle(keys, scope);
89
+ log('Toggled:', keys);
90
+ }, [manager]);
91
+ const getCheatSheet = React.useCallback((scope) => {
92
+ return manager?.getCheatSheet(scope);
93
+ }, [manager]);
94
+ const getActiveScope = React.useCallback(() => {
95
+ return manager?.getActiveScope();
96
+ }, [manager]);
97
+ const disableAll = React.useCallback((scope) => {
98
+ manager?.disableAll(scope);
99
+ log(`Disabled all shortcuts${scope ? ` in scope "${scope}"` : ''}`);
100
+ }, [manager]);
101
+ const enableAll = React.useCallback((scope) => {
102
+ manager?.enableAll(scope);
103
+ log(`Enabled all shortcuts${scope ? ` in scope "${scope}"` : ''}`);
104
+ }, [manager]);
105
+ const setScope = React.useCallback((scope) => {
106
+ manager?.setActiveScope(scope);
107
+ log('Scope set to:', scope);
108
+ }, [manager]);
109
+ const resetScope = React.useCallback(() => {
110
+ manager?.resetScope();
111
+ log('Reset scope');
112
+ }, [manager]);
113
+ const getScopes = React.useCallback(() => {
114
+ return manager?.getScopes();
115
+ }, [manager]);
116
+ const isScopeActive = React.useCallback((scope) => {
117
+ return manager?.isScopeActive(scope);
118
+ }, [manager]);
119
+ const onTyping = React.useCallback((callback) => {
120
+ manager?.onTyping(callback);
121
+ }, [manager]);
122
+ const popScope = React.useCallback(() => {
123
+ manager?.popScope();
124
+ log('Popped scope, active scope is:', manager?.getActiveScope());
125
+ }, [manager]);
126
+ const pushScope = React.useCallback((scope) => {
127
+ manager?.pushScope(scope);
128
+ log('Pushed scope:', scope);
129
+ }, [manager]);
130
+ const getScopeInfo = React.useCallback((scope) => {
131
+ return manager?.getScopesInfo(scope);
132
+ }, [manager]);
133
+ const destroy = () => {
134
+ manager?.destroy();
135
+ };
136
+ const clear = () => {
137
+ manager?.clear();
138
+ };
139
+ return {
140
+ register,
141
+ unregister,
142
+ enable,
143
+ disable,
144
+ toggle,
145
+ setScope,
146
+ getCheatSheet,
147
+ destroy,
148
+ getScopeInfo,
149
+ getActiveScope,
150
+ popScope,
151
+ pushScope,
152
+ resetScope,
153
+ getScopes,
154
+ isScopeActive,
155
+ onTyping,
156
+ enableAll,
157
+ clear,
158
+ disableAll,
159
+ manager,
160
+ };
161
+ };
162
+
163
+ export { useKeybindy };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keybindy/react",
3
- "version": "1.1.2",
3
+ "version": "1.1.3",
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",
@@ -51,13 +51,13 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "react": "^19.1.0",
54
- "@keybindy/core": "1.1.2"
54
+ "@keybindy/core": "1.1.3"
55
55
  },
56
56
  "scripts": {
57
57
  "format": "prettier --write \"src/**/*.{ts,tsx}\"",
58
58
  "prebuild": "rm -rf dist",
59
- "build": "tsup",
60
- "dev": "tsup -w",
59
+ "build": "rollup -c",
60
+ "dev": "rollup -c -w",
61
61
  "test": "vitest"
62
62
  }
63
63
  }
package/dist/index.cjs DELETED
@@ -1,282 +0,0 @@
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 getSharedInstance = (options) => {
11
- if (typeof window === "undefined") {
12
- return null;
13
- }
14
- if (!sharedInstance) {
15
- sharedInstance = new (0, _core2.default)(options);
16
- }
17
- return sharedInstance;
18
- };
19
- var useKeybindy = ({
20
- logs = false,
21
- onShortcutFired
22
- } = {}) => {
23
- const [manager, setManager] = _react2.default.useState(null);
24
- _react2.default.useEffect(() => {
25
- if (!manager) {
26
- const instance = getSharedInstance({ onShortcutFired, silent: !logs });
27
- setManager(instance);
28
- }
29
- }, []);
30
- const log = (...args) => {
31
- if (logs) console.log("[Keybindy]", ...args);
32
- };
33
- const warn = (...args) => {
34
- if (logs) console.warn("[Keybindy]", ...args);
35
- };
36
- const register = _react2.default.useCallback(
37
- (keys, handler, options) => {
38
- if (!manager) return;
39
- if (keys.length === 0) {
40
- warn("No keys provided to register");
41
- return;
42
- }
43
- const id = _optionalChain([options, 'optionalAccess', _ => _.data, 'optionalAccess', _2 => _2.id]);
44
- log("Registered:", _nullishCoalesce(id, () => ( keys)));
45
- manager.register(keys, handler, options);
46
- },
47
- [manager]
48
- );
49
- const unregister = _react2.default.useCallback(
50
- (keys, scope) => {
51
- if (!manager) return;
52
- if (keys.length === 0) {
53
- warn("No keys provided to unregister");
54
- return;
55
- }
56
- manager.unregister(keys, scope);
57
- log("Unregistered:", keys);
58
- },
59
- [manager]
60
- );
61
- const enable = _react2.default.useCallback(
62
- (keys, scope) => {
63
- if (!manager) return;
64
- if (keys.length === 0) {
65
- warn("No keys provided to enable");
66
- return;
67
- }
68
- manager.enable(keys, scope);
69
- log("Enabled:", keys);
70
- },
71
- [manager]
72
- );
73
- const disable = _react2.default.useCallback(
74
- (keys, scope) => {
75
- if (!manager) return;
76
- if (keys.length === 0) {
77
- warn("No keys provided to disable");
78
- return;
79
- }
80
- manager.disable(keys, scope);
81
- log("Disabled:", keys);
82
- },
83
- [manager]
84
- );
85
- const toggle = _react2.default.useCallback(
86
- (keys, scope) => {
87
- if (!manager) return;
88
- if (keys.length === 0) {
89
- warn("No keys provided to toggle");
90
- return;
91
- }
92
- manager.toggle(keys, scope);
93
- log("Toggled:", keys);
94
- },
95
- [manager]
96
- );
97
- const getCheatSheet = _react2.default.useCallback(
98
- (scope) => {
99
- return _optionalChain([manager, 'optionalAccess', _3 => _3.getCheatSheet, 'call', _4 => _4(scope)]);
100
- },
101
- [manager]
102
- );
103
- const getActiveScope = _react2.default.useCallback(() => {
104
- return _optionalChain([manager, 'optionalAccess', _5 => _5.getActiveScope, 'call', _6 => _6()]);
105
- }, [manager]);
106
- const disableAll = _react2.default.useCallback(
107
- (scope) => {
108
- _optionalChain([manager, 'optionalAccess', _7 => _7.disableAll, 'call', _8 => _8(scope)]);
109
- log(`Disabled all shortcuts${scope ? ` in scope "${scope}"` : ""}`);
110
- },
111
- [manager]
112
- );
113
- const enableAll = _react2.default.useCallback(
114
- (scope) => {
115
- _optionalChain([manager, 'optionalAccess', _9 => _9.enableAll, 'call', _10 => _10(scope)]);
116
- log(`Enabled all shortcuts${scope ? ` in scope "${scope}"` : ""}`);
117
- },
118
- [manager]
119
- );
120
- const setScope = _react2.default.useCallback(
121
- (scope) => {
122
- _optionalChain([manager, 'optionalAccess', _11 => _11.setActiveScope, 'call', _12 => _12(scope)]);
123
- log("Scope set to:", scope);
124
- },
125
- [manager]
126
- );
127
- const resetScope = _react2.default.useCallback(() => {
128
- _optionalChain([manager, 'optionalAccess', _13 => _13.resetScope, 'call', _14 => _14()]);
129
- log("Reset scope");
130
- }, [manager]);
131
- const getScopes = _react2.default.useCallback(() => {
132
- return _optionalChain([manager, 'optionalAccess', _15 => _15.getScopes, 'call', _16 => _16()]);
133
- }, [manager]);
134
- const isScopeActive = _react2.default.useCallback(
135
- (scope) => {
136
- return _optionalChain([manager, 'optionalAccess', _17 => _17.isScopeActive, 'call', _18 => _18(scope)]);
137
- },
138
- [manager]
139
- );
140
- const onTyping = _react2.default.useCallback(
141
- (callback) => {
142
- _optionalChain([manager, 'optionalAccess', _19 => _19.onTyping, 'call', _20 => _20(callback)]);
143
- },
144
- [manager]
145
- );
146
- const popScope = _react2.default.useCallback(() => {
147
- _optionalChain([manager, 'optionalAccess', _21 => _21.popScope, 'call', _22 => _22()]);
148
- log("Popped scope, active scope is:", _optionalChain([manager, 'optionalAccess', _23 => _23.getActiveScope, 'call', _24 => _24()]));
149
- }, [manager]);
150
- const pushScope = _react2.default.useCallback(
151
- (scope) => {
152
- _optionalChain([manager, 'optionalAccess', _25 => _25.pushScope, 'call', _26 => _26(scope)]);
153
- log("Pushed scope:", scope);
154
- },
155
- [manager]
156
- );
157
- const getScopeInfo = _react2.default.useCallback(
158
- (scope) => {
159
- return _optionalChain([manager, 'optionalAccess', _27 => _27.getScopesInfo, 'call', _28 => _28(scope)]);
160
- },
161
- [manager]
162
- );
163
- const destroy = () => {
164
- _optionalChain([manager, 'optionalAccess', _29 => _29.destroy, 'call', _30 => _30()]);
165
- };
166
- const clear = () => {
167
- _optionalChain([manager, 'optionalAccess', _31 => _31.clear, 'call', _32 => _32()]);
168
- };
169
- return {
170
- register,
171
- unregister,
172
- enable,
173
- disable,
174
- toggle,
175
- setScope,
176
- getCheatSheet,
177
- destroy,
178
- getScopeInfo,
179
- getActiveScope,
180
- popScope,
181
- pushScope,
182
- resetScope,
183
- getScopes,
184
- isScopeActive,
185
- onTyping,
186
- enableAll,
187
- clear,
188
- disableAll,
189
- manager
190
- };
191
- };
192
-
193
- // src/Keybindy.tsx
194
- var _jsxruntime = require('react/jsx-runtime');
195
- var Keybindy = ({
196
- scope = "global",
197
- shortcuts = [],
198
- children,
199
- disabled,
200
- onShortcutFired,
201
- logs = false
202
- }) => {
203
- const { register, unregister, manager, pushScope, popScope, getScopes, setScope } = useKeybindy({
204
- onShortcutFired,
205
- logs
206
- });
207
- const prevScope = _react2.default.useRef(null);
208
- _react2.default.useEffect(() => {
209
- if (!manager) {
210
- return;
211
- }
212
- prevScope.current = _nullishCoalesce(manager.getActiveScope(), () => ( "global"));
213
- if (!_optionalChain([getScopes, 'call', _33 => _33(), 'optionalAccess', _34 => _34.includes, 'call', _35 => _35(scope)])) {
214
- pushScope(scope);
215
- }
216
- setScope(scope);
217
- shortcuts.forEach(({ keys, handler, options }) => {
218
- register(keys, handler, { ...options, scope });
219
- });
220
- if (disabled) {
221
- manager.disableAll(scope);
222
- } else {
223
- manager.enableAll(scope);
224
- }
225
- return () => {
226
- shortcuts.forEach(({ keys }) => {
227
- if (Array.isArray(keys[0])) {
228
- keys.forEach((key) => unregister(key, scope));
229
- } else {
230
- unregister(keys, scope);
231
- }
232
- });
233
- popScope();
234
- };
235
- }, [scope, shortcuts, manager, disabled]);
236
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment, { children });
237
- };
238
-
239
- // src/ShortcutLabel.tsx
240
-
241
-
242
- var ShortcutLabel = ({ keys, renderKey, style, ...props }) => {
243
- const isMac = typeof navigator !== "undefined" && /Mac/.test(navigator.userAgent);
244
- const defaultRenderKey = (key) => {
245
- switch (key.toLowerCase()) {
246
- case "meta":
247
- return isMac ? "\u2318" : "Ctrl";
248
- case "ctrl":
249
- return "Ctrl";
250
- case "shift":
251
- return "\u21E7";
252
- case "alt":
253
- return isMac ? "\u2325" : "Alt";
254
- case "enter":
255
- return "\u21B5";
256
- default:
257
- return key.toUpperCase();
258
- }
259
- };
260
- 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(" + ")] : [];
261
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
262
- "kbd",
263
- {
264
- style: {
265
- fontFamily: "monospace",
266
- padding: "2.5px 5px",
267
- border: "1px solid #cccccc2f",
268
- backgroundColor: "#2e2e2e",
269
- borderRadius: "4px",
270
- userSelect: "none",
271
- ...style
272
- },
273
- ...props,
274
- children: rendered
275
- }
276
- );
277
- };
278
-
279
-
280
-
281
-
282
- exports.Keybindy = Keybindy; exports.ShortcutLabel = ShortcutLabel; exports.useKeybindy = useKeybindy;
package/dist/index.d.cts DELETED
@@ -1,188 +0,0 @@
1
- import React from 'react';
2
- import ShortcutManager, { Keys, ShortcutHandler, HoldShortcutHandler, 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 | HoldShortcutHandler;
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 | HoldShortcutHandler, 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 | undefined;
159
- popScope: () => void;
160
- pushScope: (scope: string) => void;
161
- resetScope: () => void;
162
- getScopes: () => string[] | undefined;
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 | null;
172
- };
173
- /**
174
- * React hook to manage keyboard shortcuts using a shared instance of `ShortcutManager`.
175
- * This hook is safe for server-side rendering (SSR) and will only initialize the manager on the client.
176
- *
177
- * @param {Object} config - Configuration object.
178
- * @param {boolean} [config.logs=false] - Whether to enable debug logs in the console.
179
- * @param {(info: Shortcut) => void} [config.onShortcutFired] - Callback for when a shortcut is fired.
180
- *
181
- * @returns {Object} Object containing shortcut management methods and the manager instance (null on server).
182
- */
183
- declare const useKeybindy: ({ logs, onShortcutFired, }?: {
184
- logs?: boolean;
185
- onShortcutFired?: (info: Shortcut) => void;
186
- }) => UseKeybindyReturn;
187
-
188
- export { Keybindy, ShortcutLabel, useKeybindy };
package/dist/index.mjs DELETED
@@ -1,282 +0,0 @@
1
- 'use client';
2
-
3
- // src/Keybindy.tsx
4
- import React2 from "react";
5
-
6
- // src/useKeybindy.tsx
7
- import React from "react";
8
- import ShortcutManager from "@keybindy/core";
9
- var sharedInstance = null;
10
- var getSharedInstance = (options) => {
11
- if (typeof window === "undefined") {
12
- return null;
13
- }
14
- if (!sharedInstance) {
15
- sharedInstance = new ShortcutManager(options);
16
- }
17
- return sharedInstance;
18
- };
19
- var useKeybindy = ({
20
- logs = false,
21
- onShortcutFired
22
- } = {}) => {
23
- const [manager, setManager] = React.useState(null);
24
- React.useEffect(() => {
25
- if (!manager) {
26
- const instance = getSharedInstance({ onShortcutFired, silent: !logs });
27
- setManager(instance);
28
- }
29
- }, []);
30
- const log = (...args) => {
31
- if (logs) console.log("[Keybindy]", ...args);
32
- };
33
- const warn = (...args) => {
34
- if (logs) console.warn("[Keybindy]", ...args);
35
- };
36
- const register = React.useCallback(
37
- (keys, handler, options) => {
38
- if (!manager) return;
39
- if (keys.length === 0) {
40
- warn("No keys provided to register");
41
- return;
42
- }
43
- const id = options?.data?.id;
44
- log("Registered:", id ?? keys);
45
- manager.register(keys, handler, options);
46
- },
47
- [manager]
48
- );
49
- const unregister = React.useCallback(
50
- (keys, scope) => {
51
- if (!manager) return;
52
- if (keys.length === 0) {
53
- warn("No keys provided to unregister");
54
- return;
55
- }
56
- manager.unregister(keys, scope);
57
- log("Unregistered:", keys);
58
- },
59
- [manager]
60
- );
61
- const enable = React.useCallback(
62
- (keys, scope) => {
63
- if (!manager) return;
64
- if (keys.length === 0) {
65
- warn("No keys provided to enable");
66
- return;
67
- }
68
- manager.enable(keys, scope);
69
- log("Enabled:", keys);
70
- },
71
- [manager]
72
- );
73
- const disable = React.useCallback(
74
- (keys, scope) => {
75
- if (!manager) return;
76
- if (keys.length === 0) {
77
- warn("No keys provided to disable");
78
- return;
79
- }
80
- manager.disable(keys, scope);
81
- log("Disabled:", keys);
82
- },
83
- [manager]
84
- );
85
- const toggle = React.useCallback(
86
- (keys, scope) => {
87
- if (!manager) return;
88
- if (keys.length === 0) {
89
- warn("No keys provided to toggle");
90
- return;
91
- }
92
- manager.toggle(keys, scope);
93
- log("Toggled:", keys);
94
- },
95
- [manager]
96
- );
97
- const getCheatSheet = React.useCallback(
98
- (scope) => {
99
- return manager?.getCheatSheet(scope);
100
- },
101
- [manager]
102
- );
103
- const getActiveScope = React.useCallback(() => {
104
- return manager?.getActiveScope();
105
- }, [manager]);
106
- const disableAll = React.useCallback(
107
- (scope) => {
108
- manager?.disableAll(scope);
109
- log(`Disabled all shortcuts${scope ? ` in scope "${scope}"` : ""}`);
110
- },
111
- [manager]
112
- );
113
- const enableAll = React.useCallback(
114
- (scope) => {
115
- manager?.enableAll(scope);
116
- log(`Enabled all shortcuts${scope ? ` in scope "${scope}"` : ""}`);
117
- },
118
- [manager]
119
- );
120
- const setScope = React.useCallback(
121
- (scope) => {
122
- manager?.setActiveScope(scope);
123
- log("Scope set to:", scope);
124
- },
125
- [manager]
126
- );
127
- const resetScope = React.useCallback(() => {
128
- manager?.resetScope();
129
- log("Reset scope");
130
- }, [manager]);
131
- const getScopes = React.useCallback(() => {
132
- return manager?.getScopes();
133
- }, [manager]);
134
- const isScopeActive = React.useCallback(
135
- (scope) => {
136
- return manager?.isScopeActive(scope);
137
- },
138
- [manager]
139
- );
140
- const onTyping = React.useCallback(
141
- (callback) => {
142
- manager?.onTyping(callback);
143
- },
144
- [manager]
145
- );
146
- const popScope = React.useCallback(() => {
147
- manager?.popScope();
148
- log("Popped scope, active scope is:", manager?.getActiveScope());
149
- }, [manager]);
150
- const pushScope = React.useCallback(
151
- (scope) => {
152
- manager?.pushScope(scope);
153
- log("Pushed scope:", scope);
154
- },
155
- [manager]
156
- );
157
- const getScopeInfo = React.useCallback(
158
- (scope) => {
159
- return manager?.getScopesInfo(scope);
160
- },
161
- [manager]
162
- );
163
- const destroy = () => {
164
- manager?.destroy();
165
- };
166
- const clear = () => {
167
- manager?.clear();
168
- };
169
- return {
170
- register,
171
- unregister,
172
- enable,
173
- disable,
174
- toggle,
175
- setScope,
176
- getCheatSheet,
177
- destroy,
178
- getScopeInfo,
179
- getActiveScope,
180
- popScope,
181
- pushScope,
182
- resetScope,
183
- getScopes,
184
- isScopeActive,
185
- onTyping,
186
- enableAll,
187
- clear,
188
- disableAll,
189
- manager
190
- };
191
- };
192
-
193
- // src/Keybindy.tsx
194
- import { Fragment, jsx } from "react/jsx-runtime";
195
- var Keybindy = ({
196
- scope = "global",
197
- shortcuts = [],
198
- children,
199
- disabled,
200
- onShortcutFired,
201
- logs = false
202
- }) => {
203
- const { register, unregister, manager, pushScope, popScope, getScopes, setScope } = useKeybindy({
204
- onShortcutFired,
205
- logs
206
- });
207
- const prevScope = React2.useRef(null);
208
- React2.useEffect(() => {
209
- if (!manager) {
210
- return;
211
- }
212
- prevScope.current = manager.getActiveScope() ?? "global";
213
- if (!getScopes()?.includes(scope)) {
214
- pushScope(scope);
215
- }
216
- setScope(scope);
217
- shortcuts.forEach(({ keys, handler, options }) => {
218
- register(keys, handler, { ...options, scope });
219
- });
220
- if (disabled) {
221
- manager.disableAll(scope);
222
- } else {
223
- manager.enableAll(scope);
224
- }
225
- return () => {
226
- shortcuts.forEach(({ keys }) => {
227
- if (Array.isArray(keys[0])) {
228
- keys.forEach((key) => unregister(key, scope));
229
- } else {
230
- unregister(keys, scope);
231
- }
232
- });
233
- popScope();
234
- };
235
- }, [scope, shortcuts, manager, disabled]);
236
- return /* @__PURE__ */ jsx(Fragment, { children });
237
- };
238
-
239
- // src/ShortcutLabel.tsx
240
- import React3 from "react";
241
- import { jsx as jsx2 } from "react/jsx-runtime";
242
- var ShortcutLabel = ({ keys, renderKey, style, ...props }) => {
243
- const isMac = typeof navigator !== "undefined" && /Mac/.test(navigator.userAgent);
244
- const defaultRenderKey = (key) => {
245
- switch (key.toLowerCase()) {
246
- case "meta":
247
- return isMac ? "\u2318" : "Ctrl";
248
- case "ctrl":
249
- return "Ctrl";
250
- case "shift":
251
- return "\u21E7";
252
- case "alt":
253
- return isMac ? "\u2325" : "Alt";
254
- case "enter":
255
- return "\u21B5";
256
- default:
257
- return key.toUpperCase();
258
- }
259
- };
260
- const rendered = renderKey ? keys.map((key, i) => /* @__PURE__ */ jsx2(React3.Fragment, { children: renderKey(key, i, keys) }, i)) : defaultRenderKey ? [keys.map((key) => defaultRenderKey(key)).join(" + ")] : [];
261
- return /* @__PURE__ */ jsx2(
262
- "kbd",
263
- {
264
- style: {
265
- fontFamily: "monospace",
266
- padding: "2.5px 5px",
267
- border: "1px solid #cccccc2f",
268
- backgroundColor: "#2e2e2e",
269
- borderRadius: "4px",
270
- userSelect: "none",
271
- ...style
272
- },
273
- ...props,
274
- children: rendered
275
- }
276
- );
277
- };
278
- export {
279
- Keybindy,
280
- ShortcutLabel,
281
- useKeybindy
282
- };