@keybindy/react 1.1.1 → 1.1.2

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 CHANGED
@@ -7,18 +7,26 @@ var _react = require('react'); var _react2 = _interopRequireDefault(_react);
7
7
 
8
8
  var _core = require('@keybindy/core'); var _core2 = _interopRequireDefault(_core);
9
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
+ };
10
19
  var useKeybindy = ({
11
20
  logs = false,
12
21
  onShortcutFired
13
22
  } = {}) => {
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
- }
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
+ }, []);
22
30
  const log = (...args) => {
23
31
  if (logs) console.log("[Keybindy]", ...args);
24
32
  };
@@ -27,99 +35,136 @@ var useKeybindy = ({
27
35
  };
28
36
  const register = _react2.default.useCallback(
29
37
  (keys, handler, options) => {
38
+ if (!manager) return;
30
39
  if (keys.length === 0) {
31
40
  warn("No keys provided to register");
32
41
  return;
33
42
  }
34
43
  const id = _optionalChain([options, 'optionalAccess', _ => _.data, 'optionalAccess', _2 => _2.id]);
35
- if (id) registeredIds.current.add(id);
36
44
  log("Registered:", _nullishCoalesce(id, () => ( keys)));
37
- _optionalChain([managerRef, 'access', _3 => _3.current, 'optionalAccess', _4 => _4.register, 'call', _5 => _5(keys, handler, options)]);
45
+ manager.register(keys, handler, options);
38
46
  },
39
- []
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]
40
102
  );
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
103
  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
- }, []);
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
+ );
91
127
  const resetScope = _react2.default.useCallback(() => {
92
- _optionalChain([managerRef, 'access', _33 => _33.current, 'optionalAccess', _34 => _34.resetScope, 'call', _35 => _35()]);
128
+ _optionalChain([manager, 'optionalAccess', _13 => _13.resetScope, 'call', _14 => _14()]);
93
129
  log("Reset scope");
94
- }, []);
130
+ }, [manager]);
95
131
  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
- }, []);
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
+ );
101
140
  const onTyping = _react2.default.useCallback(
102
141
  (callback) => {
103
- _optionalChain([managerRef, 'access', _42 => _42.current, 'optionalAccess', _43 => _43.onTyping, 'call', _44 => _44(callback)]);
142
+ _optionalChain([manager, 'optionalAccess', _19 => _19.onTyping, 'call', _20 => _20(callback)]);
104
143
  },
105
- []
144
+ [manager]
106
145
  );
107
146
  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
- }, []);
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
+ );
118
163
  const destroy = () => {
119
- _optionalChain([managerRef, 'access', _57 => _57.current, 'optionalAccess', _58 => _58.destroy, 'call', _59 => _59()]);
164
+ _optionalChain([manager, 'optionalAccess', _29 => _29.destroy, 'call', _30 => _30()]);
120
165
  };
121
166
  const clear = () => {
122
- _optionalChain([managerRef, 'access', _60 => _60.current, 'optionalAccess', _61 => _61.clear, 'call', _62 => _62()]);
167
+ _optionalChain([manager, 'optionalAccess', _31 => _31.clear, 'call', _32 => _32()]);
123
168
  };
124
169
  return {
125
170
  register,
@@ -141,7 +186,7 @@ var useKeybindy = ({
141
186
  enableAll,
142
187
  clear,
143
188
  disableAll,
144
- manager: managerRef.current
189
+ manager
145
190
  };
146
191
  };
147
192
 
@@ -161,8 +206,11 @@ var Keybindy = ({
161
206
  });
162
207
  const prevScope = _react2.default.useRef(null);
163
208
  _react2.default.useEffect(() => {
164
- prevScope.current = manager.getActiveScope();
165
- if (!_optionalChain([getScopes, 'call', _63 => _63(), 'optionalAccess', _64 => _64.includes, 'call', _65 => _65(scope)])) {
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)])) {
166
214
  pushScope(scope);
167
215
  }
168
216
  setScope(scope);
@@ -171,6 +219,8 @@ var Keybindy = ({
171
219
  });
172
220
  if (disabled) {
173
221
  manager.disableAll(scope);
222
+ } else {
223
+ manager.enableAll(scope);
174
224
  }
175
225
  return () => {
176
226
  shortcuts.forEach(({ keys }) => {
@@ -182,7 +232,7 @@ var Keybindy = ({
182
232
  });
183
233
  popScope();
184
234
  };
185
- }, [scope, JSON.stringify(shortcuts)]);
235
+ }, [scope, shortcuts, manager, disabled]);
186
236
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment, { children });
187
237
  };
188
238
 
@@ -0,0 +1,188 @@
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 };
@@ -0,0 +1,188 @@
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 CHANGED
@@ -7,18 +7,26 @@ import React2 from "react";
7
7
  import React from "react";
8
8
  import ShortcutManager from "@keybindy/core";
9
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
+ };
10
19
  var useKeybindy = ({
11
20
  logs = false,
12
21
  onShortcutFired
13
22
  } = {}) => {
14
- const managerRef = React.useRef(null);
15
- const registeredIds = React.useRef(/* @__PURE__ */ new Set());
16
- if (!sharedInstance) {
17
- sharedInstance = new ShortcutManager({ onShortcutFired, silent: !logs });
18
- }
19
- if (!managerRef.current) {
20
- managerRef.current = sharedInstance;
21
- }
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
+ }, []);
22
30
  const log = (...args) => {
23
31
  if (logs) console.log("[Keybindy]", ...args);
24
32
  };
@@ -27,99 +35,136 @@ var useKeybindy = ({
27
35
  };
28
36
  const register = React.useCallback(
29
37
  (keys, handler, options) => {
38
+ if (!manager) return;
30
39
  if (keys.length === 0) {
31
40
  warn("No keys provided to register");
32
41
  return;
33
42
  }
34
43
  const id = options?.data?.id;
35
- if (id) registeredIds.current.add(id);
36
44
  log("Registered:", id ?? keys);
37
- managerRef.current?.register(keys, handler, options);
45
+ manager.register(keys, handler, options);
38
46
  },
39
- []
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]
40
102
  );
41
- const unregister = React.useCallback((keys, scope) => {
42
- if (keys.length === 0) {
43
- warn("No keys provided to unregister");
44
- return;
45
- }
46
- managerRef.current?.unregister(keys, scope);
47
- log("Unregistered:", keys);
48
- }, []);
49
- const enable = React.useCallback((keys, scope) => {
50
- if (keys.length === 0) {
51
- warn("No keys provided to enable");
52
- return;
53
- }
54
- managerRef.current?.enable(keys, scope);
55
- log("Enabled:", keys);
56
- }, []);
57
- const disable = React.useCallback((keys, scope) => {
58
- if (keys.length === 0) {
59
- warn("No keys provided to disable");
60
- return;
61
- }
62
- managerRef.current?.disable(keys, scope);
63
- log("Disabled:", keys);
64
- }, []);
65
- const toggle = React.useCallback((keys, scope) => {
66
- if (keys.length === 0) {
67
- warn("No keys provided to toggle");
68
- return;
69
- }
70
- managerRef.current?.toggle(keys, scope);
71
- log("Toggled:", keys);
72
- }, []);
73
- const getCheatSheet = React.useCallback((scope) => {
74
- return managerRef.current?.getCheatSheet(scope);
75
- }, []);
76
103
  const getActiveScope = React.useCallback(() => {
77
- return managerRef.current?.getActiveScope() ?? "";
78
- }, []);
79
- const disableAll = React.useCallback((scope) => {
80
- managerRef.current?.disableAll(scope);
81
- log(`Disabled all shortcuts${scope ? ` in scope "${scope}"` : ""}`);
82
- }, []);
83
- const enableAll = React.useCallback((scope) => {
84
- managerRef.current?.enableAll(scope);
85
- log(`Enabled all shortcuts${scope ? ` in scope "${scope}"` : ""}`);
86
- }, []);
87
- const setScope = React.useCallback((scope) => {
88
- managerRef.current?.setActiveScope(scope);
89
- log("Scope set to:", scope);
90
- }, []);
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
+ );
91
127
  const resetScope = React.useCallback(() => {
92
- managerRef.current?.resetScope();
128
+ manager?.resetScope();
93
129
  log("Reset scope");
94
- }, []);
130
+ }, [manager]);
95
131
  const getScopes = React.useCallback(() => {
96
- return managerRef.current?.getScopes() ?? [];
97
- }, []);
98
- const isScopeActive = React.useCallback((scope) => {
99
- return managerRef.current?.isScopeActive(scope);
100
- }, []);
132
+ return manager?.getScopes();
133
+ }, [manager]);
134
+ const isScopeActive = React.useCallback(
135
+ (scope) => {
136
+ return manager?.isScopeActive(scope);
137
+ },
138
+ [manager]
139
+ );
101
140
  const onTyping = React.useCallback(
102
141
  (callback) => {
103
- managerRef.current?.onTyping(callback);
142
+ manager?.onTyping(callback);
104
143
  },
105
- []
144
+ [manager]
106
145
  );
107
146
  const popScope = React.useCallback(() => {
108
- managerRef.current?.popScope();
109
- log("Popped scope, active scope is:", managerRef.current?.getActiveScope());
110
- }, []);
111
- const pushScope = React.useCallback((scope) => {
112
- managerRef.current?.pushScope(scope);
113
- log("Pushed scope:", scope);
114
- }, []);
115
- const getScopeInfo = React.useCallback((scope) => {
116
- return managerRef.current?.getScopesInfo(scope);
117
- }, []);
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
+ );
118
163
  const destroy = () => {
119
- managerRef.current?.destroy();
164
+ manager?.destroy();
120
165
  };
121
166
  const clear = () => {
122
- managerRef.current?.clear();
167
+ manager?.clear();
123
168
  };
124
169
  return {
125
170
  register,
@@ -141,7 +186,7 @@ var useKeybindy = ({
141
186
  enableAll,
142
187
  clear,
143
188
  disableAll,
144
- manager: managerRef.current
189
+ manager
145
190
  };
146
191
  };
147
192
 
@@ -161,7 +206,10 @@ var Keybindy = ({
161
206
  });
162
207
  const prevScope = React2.useRef(null);
163
208
  React2.useEffect(() => {
164
- prevScope.current = manager.getActiveScope();
209
+ if (!manager) {
210
+ return;
211
+ }
212
+ prevScope.current = manager.getActiveScope() ?? "global";
165
213
  if (!getScopes()?.includes(scope)) {
166
214
  pushScope(scope);
167
215
  }
@@ -171,6 +219,8 @@ var Keybindy = ({
171
219
  });
172
220
  if (disabled) {
173
221
  manager.disableAll(scope);
222
+ } else {
223
+ manager.enableAll(scope);
174
224
  }
175
225
  return () => {
176
226
  shortcuts.forEach(({ keys }) => {
@@ -182,7 +232,7 @@ var Keybindy = ({
182
232
  });
183
233
  popScope();
184
234
  };
185
- }, [scope, JSON.stringify(shortcuts)]);
235
+ }, [scope, shortcuts, manager, disabled]);
186
236
  return /* @__PURE__ */ jsx(Fragment, { children });
187
237
  };
188
238
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keybindy/react",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
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,7 +51,7 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "react": "^19.1.0",
54
- "@keybindy/core": "1.1.1"
54
+ "@keybindy/core": "1.1.2"
55
55
  },
56
56
  "scripts": {
57
57
  "format": "prettier --write \"src/**/*.{ts,tsx}\"",