@tanstack/react-hotkeys 0.4.2 → 0.5.1

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,60 @@
1
+ import { UseHotkeyOptions } from "./useHotkey.cjs";
2
+ import { HotkeyCallback, RegisterableHotkey } from "@tanstack/hotkeys";
3
+
4
+ //#region src/useHotkeys.d.ts
5
+ /**
6
+ * A single hotkey definition for use with `useHotkeys`.
7
+ */
8
+ interface UseHotkeyDefinition {
9
+ /** The hotkey string (e.g., 'Mod+S', 'Escape') or RawHotkey object */
10
+ hotkey: RegisterableHotkey;
11
+ /** The function to call when the hotkey is pressed */
12
+ callback: HotkeyCallback;
13
+ /** Per-hotkey options (merged on top of commonOptions) */
14
+ options?: UseHotkeyOptions;
15
+ }
16
+ /**
17
+ * React hook for registering multiple keyboard hotkeys at once.
18
+ *
19
+ * Uses the singleton HotkeyManager for efficient event handling.
20
+ * Accepts a dynamic array of hotkey definitions, making it safe to use
21
+ * with variable-length lists without violating the rules of hooks.
22
+ *
23
+ * Options are merged in this order:
24
+ * HotkeysProvider defaults < commonOptions < per-definition options
25
+ *
26
+ * Callbacks and options are synced on every render to avoid stale closures.
27
+ *
28
+ * @param hotkeys - Array of hotkey definitions to register
29
+ * @param commonOptions - Shared options applied to all hotkeys (overridden by per-definition options)
30
+ *
31
+ * @example
32
+ * ```tsx
33
+ * function Editor() {
34
+ * useHotkeys([
35
+ * { hotkey: 'Mod+S', callback: () => save() },
36
+ * { hotkey: 'Mod+Z', callback: () => undo() },
37
+ * { hotkey: 'Escape', callback: () => close() },
38
+ * ])
39
+ * }
40
+ * ```
41
+ *
42
+ * @example
43
+ * ```tsx
44
+ * function MenuShortcuts({ items }) {
45
+ * // Dynamic hotkeys from data -- safe because it's a single hook call
46
+ * useHotkeys(
47
+ * items.map((item) => ({
48
+ * hotkey: item.shortcut,
49
+ * callback: item.action,
50
+ * options: { enabled: item.enabled },
51
+ * })),
52
+ * { preventDefault: true },
53
+ * )
54
+ * }
55
+ * ```
56
+ */
57
+ declare function useHotkeys(hotkeys: Array<UseHotkeyDefinition>, commonOptions?: UseHotkeyOptions): void;
58
+ //#endregion
59
+ export { UseHotkeyDefinition, useHotkeys };
60
+ //# sourceMappingURL=useHotkeys.d.cts.map
@@ -0,0 +1,60 @@
1
+ import { UseHotkeyOptions } from "./useHotkey.js";
2
+ import { HotkeyCallback, RegisterableHotkey } from "@tanstack/hotkeys";
3
+
4
+ //#region src/useHotkeys.d.ts
5
+ /**
6
+ * A single hotkey definition for use with `useHotkeys`.
7
+ */
8
+ interface UseHotkeyDefinition {
9
+ /** The hotkey string (e.g., 'Mod+S', 'Escape') or RawHotkey object */
10
+ hotkey: RegisterableHotkey;
11
+ /** The function to call when the hotkey is pressed */
12
+ callback: HotkeyCallback;
13
+ /** Per-hotkey options (merged on top of commonOptions) */
14
+ options?: UseHotkeyOptions;
15
+ }
16
+ /**
17
+ * React hook for registering multiple keyboard hotkeys at once.
18
+ *
19
+ * Uses the singleton HotkeyManager for efficient event handling.
20
+ * Accepts a dynamic array of hotkey definitions, making it safe to use
21
+ * with variable-length lists without violating the rules of hooks.
22
+ *
23
+ * Options are merged in this order:
24
+ * HotkeysProvider defaults < commonOptions < per-definition options
25
+ *
26
+ * Callbacks and options are synced on every render to avoid stale closures.
27
+ *
28
+ * @param hotkeys - Array of hotkey definitions to register
29
+ * @param commonOptions - Shared options applied to all hotkeys (overridden by per-definition options)
30
+ *
31
+ * @example
32
+ * ```tsx
33
+ * function Editor() {
34
+ * useHotkeys([
35
+ * { hotkey: 'Mod+S', callback: () => save() },
36
+ * { hotkey: 'Mod+Z', callback: () => undo() },
37
+ * { hotkey: 'Escape', callback: () => close() },
38
+ * ])
39
+ * }
40
+ * ```
41
+ *
42
+ * @example
43
+ * ```tsx
44
+ * function MenuShortcuts({ items }) {
45
+ * // Dynamic hotkeys from data -- safe because it's a single hook call
46
+ * useHotkeys(
47
+ * items.map((item) => ({
48
+ * hotkey: item.shortcut,
49
+ * callback: item.action,
50
+ * options: { enabled: item.enabled },
51
+ * })),
52
+ * { preventDefault: true },
53
+ * )
54
+ * }
55
+ * ```
56
+ */
57
+ declare function useHotkeys(hotkeys: Array<UseHotkeyDefinition>, commonOptions?: UseHotkeyOptions): void;
58
+ //#endregion
59
+ export { UseHotkeyDefinition, useHotkeys };
60
+ //# sourceMappingURL=useHotkeys.d.ts.map
@@ -0,0 +1,137 @@
1
+ import { useDefaultHotkeysOptions } from "./HotkeysProvider.js";
2
+ import { isRef } from "./utils.js";
3
+ import { detectPlatform, formatHotkey, getHotkeyManager, rawHotkeyToParsedHotkey } from "@tanstack/hotkeys";
4
+ import { useEffect, useRef } from "react";
5
+
6
+ //#region src/useHotkeys.ts
7
+ /**
8
+ * React hook for registering multiple keyboard hotkeys at once.
9
+ *
10
+ * Uses the singleton HotkeyManager for efficient event handling.
11
+ * Accepts a dynamic array of hotkey definitions, making it safe to use
12
+ * with variable-length lists without violating the rules of hooks.
13
+ *
14
+ * Options are merged in this order:
15
+ * HotkeysProvider defaults < commonOptions < per-definition options
16
+ *
17
+ * Callbacks and options are synced on every render to avoid stale closures.
18
+ *
19
+ * @param hotkeys - Array of hotkey definitions to register
20
+ * @param commonOptions - Shared options applied to all hotkeys (overridden by per-definition options)
21
+ *
22
+ * @example
23
+ * ```tsx
24
+ * function Editor() {
25
+ * useHotkeys([
26
+ * { hotkey: 'Mod+S', callback: () => save() },
27
+ * { hotkey: 'Mod+Z', callback: () => undo() },
28
+ * { hotkey: 'Escape', callback: () => close() },
29
+ * ])
30
+ * }
31
+ * ```
32
+ *
33
+ * @example
34
+ * ```tsx
35
+ * function MenuShortcuts({ items }) {
36
+ * // Dynamic hotkeys from data -- safe because it's a single hook call
37
+ * useHotkeys(
38
+ * items.map((item) => ({
39
+ * hotkey: item.shortcut,
40
+ * callback: item.action,
41
+ * options: { enabled: item.enabled },
42
+ * })),
43
+ * { preventDefault: true },
44
+ * )
45
+ * }
46
+ * ```
47
+ */
48
+ function useHotkeys(hotkeys, commonOptions = {}) {
49
+ const defaultOptions = useDefaultHotkeysOptions().hotkey;
50
+ const manager = getHotkeyManager();
51
+ const platform = commonOptions.platform ?? defaultOptions?.platform ?? detectPlatform();
52
+ const registrationsRef = useRef(/* @__PURE__ */ new Map());
53
+ const hotkeysRef = useRef(hotkeys);
54
+ const hotkeyStringsRef = useRef([]);
55
+ const commonOptionsRef = useRef(commonOptions);
56
+ const defaultOptionsRef = useRef(defaultOptions);
57
+ const managerRef = useRef(manager);
58
+ const hotkeyStrings = hotkeys.map((def) => typeof def.hotkey === "string" ? def.hotkey : formatHotkey(rawHotkeyToParsedHotkey(def.hotkey, platform)));
59
+ hotkeysRef.current = hotkeys;
60
+ hotkeyStringsRef.current = hotkeyStrings;
61
+ commonOptionsRef.current = commonOptions;
62
+ defaultOptionsRef.current = defaultOptions;
63
+ managerRef.current = manager;
64
+ useEffect(() => {
65
+ const prevRegistrations = registrationsRef.current;
66
+ const nextRegistrations = /* @__PURE__ */ new Map();
67
+ const rows = [];
68
+ for (let i = 0; i < hotkeysRef.current.length; i++) {
69
+ const def = hotkeysRef.current[i];
70
+ const hotkeyStr = hotkeyStringsRef.current[i];
71
+ const mergedOptions = {
72
+ ...defaultOptionsRef.current,
73
+ ...commonOptionsRef.current,
74
+ ...def.options
75
+ };
76
+ const resolvedTarget = isRef(mergedOptions.target) ? mergedOptions.target.current : mergedOptions.target ?? (typeof document !== "undefined" ? document : null);
77
+ if (!resolvedTarget) continue;
78
+ const registrationKey = `${i}:${hotkeyStr}`;
79
+ rows.push({
80
+ registrationKey,
81
+ def,
82
+ hotkeyStr,
83
+ mergedOptions,
84
+ resolvedTarget
85
+ });
86
+ }
87
+ const nextKeys = new Set(rows.map((r) => r.registrationKey));
88
+ for (const [key, record] of prevRegistrations) if (!nextKeys.has(key) && record.handle.isActive) record.handle.unregister();
89
+ for (const row of rows) {
90
+ const { registrationKey, def, hotkeyStr, mergedOptions, resolvedTarget } = row;
91
+ const existing = prevRegistrations.get(registrationKey);
92
+ if (existing?.handle.isActive && existing.target === resolvedTarget) {
93
+ nextRegistrations.set(registrationKey, existing);
94
+ continue;
95
+ }
96
+ if (existing?.handle.isActive) existing.handle.unregister();
97
+ const handle = managerRef.current.register(hotkeyStr, def.callback, {
98
+ ...mergedOptions,
99
+ target: resolvedTarget
100
+ });
101
+ nextRegistrations.set(registrationKey, {
102
+ handle,
103
+ target: resolvedTarget
104
+ });
105
+ }
106
+ registrationsRef.current = nextRegistrations;
107
+ return () => {
108
+ for (const { handle } of registrationsRef.current.values()) if (handle.isActive) handle.unregister();
109
+ registrationsRef.current = /* @__PURE__ */ new Map();
110
+ };
111
+ }, [hotkeyStrings.join("\0"), hotkeys.map((def) => {
112
+ return {
113
+ ...defaultOptions,
114
+ ...commonOptions,
115
+ ...def.options
116
+ }.enabled ?? true;
117
+ }).join("\0")]);
118
+ for (let i = 0; i < hotkeys.length; i++) {
119
+ const def = hotkeys[i];
120
+ const hotkeyStr = hotkeyStrings[i];
121
+ const registrationKey = `${i}:${hotkeyStr}`;
122
+ const handle = registrationsRef.current.get(registrationKey)?.handle;
123
+ if (handle?.isActive) {
124
+ handle.callback = def.callback;
125
+ const { target: _target, ...optionsWithoutTarget } = {
126
+ ...defaultOptions,
127
+ ...commonOptions,
128
+ ...def.options
129
+ };
130
+ handle.setOptions(optionsWithoutTarget);
131
+ }
132
+ }
133
+ }
134
+
135
+ //#endregion
136
+ export { useHotkeys };
137
+ //# sourceMappingURL=useHotkeys.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useHotkeys.js","names":[],"sources":["../src/useHotkeys.ts"],"sourcesContent":["import { useEffect, useRef } from 'react'\nimport {\n detectPlatform,\n formatHotkey,\n getHotkeyManager,\n rawHotkeyToParsedHotkey,\n} from '@tanstack/hotkeys'\nimport { useDefaultHotkeysOptions } from './HotkeysProvider'\nimport { isRef } from './utils'\nimport type { UseHotkeyOptions } from './useHotkey'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyRegistrationHandle,\n RegisterableHotkey,\n} from '@tanstack/hotkeys'\n\n/**\n * A single hotkey definition for use with `useHotkeys`.\n */\nexport interface UseHotkeyDefinition {\n /** The hotkey string (e.g., 'Mod+S', 'Escape') or RawHotkey object */\n hotkey: RegisterableHotkey\n /** The function to call when the hotkey is pressed */\n callback: HotkeyCallback\n /** Per-hotkey options (merged on top of commonOptions) */\n options?: UseHotkeyOptions\n}\n\n/**\n * React hook for registering multiple keyboard hotkeys at once.\n *\n * Uses the singleton HotkeyManager for efficient event handling.\n * Accepts a dynamic array of hotkey definitions, making it safe to use\n * with variable-length lists without violating the rules of hooks.\n *\n * Options are merged in this order:\n * HotkeysProvider defaults < commonOptions < per-definition options\n *\n * Callbacks and options are synced on every render to avoid stale closures.\n *\n * @param hotkeys - Array of hotkey definitions to register\n * @param commonOptions - Shared options applied to all hotkeys (overridden by per-definition options)\n *\n * @example\n * ```tsx\n * function Editor() {\n * useHotkeys([\n * { hotkey: 'Mod+S', callback: () => save() },\n * { hotkey: 'Mod+Z', callback: () => undo() },\n * { hotkey: 'Escape', callback: () => close() },\n * ])\n * }\n * ```\n *\n * @example\n * ```tsx\n * function MenuShortcuts({ items }) {\n * // Dynamic hotkeys from data -- safe because it's a single hook call\n * useHotkeys(\n * items.map((item) => ({\n * hotkey: item.shortcut,\n * callback: item.action,\n * options: { enabled: item.enabled },\n * })),\n * { preventDefault: true },\n * )\n * }\n * ```\n */\nexport function useHotkeys(\n hotkeys: Array<UseHotkeyDefinition>,\n commonOptions: UseHotkeyOptions = {},\n): void {\n type RegistrationRecord = {\n handle: HotkeyRegistrationHandle\n target: Document | HTMLElement | Window\n }\n\n const defaultOptions = useDefaultHotkeysOptions().hotkey\n const manager = getHotkeyManager()\n const platform =\n commonOptions.platform ?? defaultOptions?.platform ?? detectPlatform()\n\n const registrationsRef = useRef<Map<string, RegistrationRecord>>(new Map())\n const hotkeysRef = useRef(hotkeys)\n const hotkeyStringsRef = useRef<Array<Hotkey>>([])\n const commonOptionsRef = useRef(commonOptions)\n const defaultOptionsRef = useRef(defaultOptions)\n const managerRef = useRef(manager)\n\n const hotkeyStrings = hotkeys.map((def) =>\n typeof def.hotkey === 'string'\n ? def.hotkey\n : (formatHotkey(rawHotkeyToParsedHotkey(def.hotkey, platform)) as Hotkey),\n )\n\n hotkeysRef.current = hotkeys\n hotkeyStringsRef.current = hotkeyStrings\n commonOptionsRef.current = commonOptions\n defaultOptionsRef.current = defaultOptions\n managerRef.current = manager\n\n // Stable serialized keys for effect dependencies\n const hotkeyKey = hotkeyStrings.join('\\0')\n const enabledKey = hotkeys\n .map((def) => {\n const merged = {\n ...defaultOptions,\n ...commonOptions,\n ...def.options,\n }\n return merged.enabled ?? true\n })\n .join('\\0')\n\n useEffect(() => {\n const prevRegistrations = registrationsRef.current\n const nextRegistrations = new Map<string, RegistrationRecord>()\n\n const rows: Array<{\n registrationKey: string\n def: (typeof hotkeysRef.current)[number]\n hotkeyStr: Hotkey\n mergedOptions: UseHotkeyOptions\n resolvedTarget: Document | HTMLElement | Window\n }> = []\n\n for (let i = 0; i < hotkeysRef.current.length; i++) {\n const def = hotkeysRef.current[i]!\n const hotkeyStr = hotkeyStringsRef.current[i]!\n const mergedOptions = {\n ...defaultOptionsRef.current,\n ...commonOptionsRef.current,\n ...def.options,\n } as UseHotkeyOptions\n\n const resolvedTarget = isRef(mergedOptions.target)\n ? mergedOptions.target.current\n : (mergedOptions.target ??\n (typeof document !== 'undefined' ? document : null))\n\n if (!resolvedTarget) {\n continue\n }\n\n const registrationKey = `${i}:${hotkeyStr}`\n rows.push({\n registrationKey,\n def,\n hotkeyStr,\n mergedOptions,\n resolvedTarget,\n })\n }\n\n const nextKeys = new Set(rows.map((r) => r.registrationKey))\n\n for (const [key, record] of prevRegistrations) {\n if (!nextKeys.has(key) && record.handle.isActive) {\n record.handle.unregister()\n }\n }\n\n for (const row of rows) {\n const { registrationKey, def, hotkeyStr, mergedOptions, resolvedTarget } =\n row\n\n const existing = prevRegistrations.get(registrationKey)\n if (existing?.handle.isActive && existing.target === resolvedTarget) {\n nextRegistrations.set(registrationKey, existing)\n continue\n }\n\n if (existing?.handle.isActive) {\n existing.handle.unregister()\n }\n\n const handle = managerRef.current.register(hotkeyStr, def.callback, {\n ...mergedOptions,\n target: resolvedTarget,\n })\n nextRegistrations.set(registrationKey, {\n handle,\n target: resolvedTarget,\n })\n }\n\n registrationsRef.current = nextRegistrations\n\n return () => {\n for (const { handle } of registrationsRef.current.values()) {\n if (handle.isActive) {\n handle.unregister()\n }\n }\n registrationsRef.current = new Map()\n }\n }, [hotkeyKey, enabledKey])\n\n // Sync callbacks and options on EVERY render (outside useEffect)\n for (let i = 0; i < hotkeys.length; i++) {\n const def = hotkeys[i]!\n const hotkeyStr = hotkeyStrings[i]!\n const registrationKey = `${i}:${hotkeyStr}`\n const handle = registrationsRef.current.get(registrationKey)?.handle\n\n if (handle?.isActive) {\n handle.callback = def.callback\n const mergedOptions = {\n ...defaultOptions,\n ...commonOptions,\n ...def.options,\n } as UseHotkeyOptions\n const { target: _target, ...optionsWithoutTarget } = mergedOptions\n handle.setOptions(optionsWithoutTarget)\n }\n }\n}\n"],"mappings":"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"}
package/dist/utils.cjs ADDED
@@ -0,0 +1,12 @@
1
+
2
+ //#region src/utils.ts
3
+ /**
4
+ * Type guard to check if a value is a React ref-like object.
5
+ */
6
+ function isRef(value) {
7
+ return value !== null && typeof value === "object" && "current" in value;
8
+ }
9
+
10
+ //#endregion
11
+ exports.isRef = isRef;
12
+ //# sourceMappingURL=utils.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.cjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import type React from 'react'\n\n/**\n * Type guard to check if a value is a React ref-like object.\n */\nexport function isRef(\n value: unknown,\n): value is React.RefObject<HTMLElement | null> {\n return value !== null && typeof value === 'object' && 'current' in value\n}\n"],"mappings":";;;;;AAKA,SAAgB,MACd,OAC8C;AAC9C,QAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,aAAa"}
package/dist/utils.js ADDED
@@ -0,0 +1,11 @@
1
+ //#region src/utils.ts
2
+ /**
3
+ * Type guard to check if a value is a React ref-like object.
4
+ */
5
+ function isRef(value) {
6
+ return value !== null && typeof value === "object" && "current" in value;
7
+ }
8
+
9
+ //#endregion
10
+ export { isRef };
11
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import type React from 'react'\n\n/**\n * Type guard to check if a value is a React ref-like object.\n */\nexport function isRef(\n value: unknown,\n): value is React.RefObject<HTMLElement | null> {\n return value !== null && typeof value === 'object' && 'current' in value\n}\n"],"mappings":";;;;AAKA,SAAgB,MACd,OAC8C;AAC9C,QAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,aAAa"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/react-hotkeys",
3
- "version": "0.4.2",
3
+ "version": "0.5.1",
4
4
  "description": "React adapter for TanStack Hotkeys",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -40,13 +40,13 @@
40
40
  ],
41
41
  "dependencies": {
42
42
  "@tanstack/react-store": "^0.9.2",
43
- "@tanstack/hotkeys": "0.4.2"
43
+ "@tanstack/hotkeys": "0.4.3"
44
44
  },
45
45
  "devDependencies": {
46
- "@eslint-react/eslint-plugin": "^2.13.0",
46
+ "@eslint-react/eslint-plugin": "^3.0.0",
47
47
  "@testing-library/react": "^16.3.2",
48
48
  "@types/react": "^19.2.14",
49
- "@vitejs/plugin-react": "^5.1.4",
49
+ "@vitejs/plugin-react": "^6.0.1",
50
50
  "eslint-plugin-react-compiler": "19.1.0-rc.2",
51
51
  "eslint-plugin-react-hooks": "^7.0.1",
52
52
  "react": "^19.2.4",
package/src/index.ts CHANGED
@@ -6,6 +6,7 @@ export * from './HotkeysProvider'
6
6
 
7
7
  // React-specific exports
8
8
  export * from './useHotkey'
9
+ export * from './useHotkeys'
9
10
  export * from './useHeldKeys'
10
11
  export * from './useHeldKeyCodes'
11
12
  export * from './useKeyHold'
package/src/useHotkey.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  rawHotkeyToParsedHotkey,
7
7
  } from '@tanstack/hotkeys'
8
8
  import { useDefaultHotkeysOptions } from './HotkeysProvider'
9
+ import { isRef } from './utils'
9
10
  import type {
10
11
  Hotkey,
11
12
  HotkeyCallback,
@@ -182,10 +183,3 @@ export function useHotkey(
182
183
  registrationRef.current.setOptions(optionsWithoutTarget)
183
184
  }
184
185
  }
185
-
186
- /**
187
- * Type guard to check if a value is a React ref-like object.
188
- */
189
- function isRef(value: unknown): value is React.RefObject<HTMLElement | null> {
190
- return value !== null && typeof value === 'object' && 'current' in value
191
- }
@@ -1,6 +1,7 @@
1
1
  import { useEffect, useRef } from 'react'
2
2
  import { formatHotkeySequence, getSequenceManager } from '@tanstack/hotkeys'
3
3
  import { useDefaultHotkeysOptions } from './HotkeysProvider'
4
+ import { isRef } from './utils'
4
5
  import type {
5
6
  HotkeyCallback,
6
7
  HotkeyCallbackContext,
@@ -32,6 +33,11 @@ export interface UseHotkeySequenceOptions extends Omit<
32
33
  * This hook allows you to register multi-key sequences like 'g g' or 'd d'
33
34
  * that trigger when the full sequence is pressed within a timeout.
34
35
  *
36
+ * Each step may include modifiers. You can chain the same modifier across
37
+ * steps (e.g. `Shift+R` then `Shift+T`). Modifier-only keydown events (Shift,
38
+ * Control, Alt, or Meta pressed alone) are ignored while matching—they do not
39
+ * advance the sequence or reset progress.
40
+ *
35
41
  * @param sequence - Array of hotkey strings that form the sequence
36
42
  * @param callback - Function to call when the sequence is completed
37
43
  * @param options - Options for the sequence behavior
@@ -54,6 +60,11 @@ export interface UseHotkeySequenceOptions extends Omit<
54
60
  * deleteInnerWord()
55
61
  * }, { timeout: 500 })
56
62
  *
63
+ * // Same modifier on consecutive steps (bare Shift between chords is ignored)
64
+ * useHotkeySequence(['Shift+R', 'Shift+T'], () => {
65
+ * nextAction()
66
+ * })
67
+ *
57
68
  * return <div>...</div>
58
69
  * }
59
70
  * ```
@@ -77,11 +88,13 @@ export function useHotkeySequence(
77
88
  const callbackRef = useRef(callback)
78
89
  const optionsRef = useRef(mergedOptions)
79
90
  const managerRef = useRef(manager)
91
+ const sequenceRef = useRef(sequence)
80
92
 
81
93
  // Update refs on every render
82
94
  callbackRef.current = callback
83
95
  optionsRef.current = mergedOptions
84
96
  managerRef.current = manager
97
+ sequenceRef.current = sequence
85
98
 
86
99
  // Track previous target and sequence to detect changes requiring re-registration
87
100
  const prevTargetRef = useRef<HTMLElement | Document | Window | null>(null)
@@ -94,7 +107,7 @@ export function useHotkeySequence(
94
107
  const { target: _target, ...optionsWithoutTarget } = mergedOptions
95
108
 
96
109
  useEffect(() => {
97
- if (sequence.length === 0) {
110
+ if (sequenceRef.current.length === 0) {
98
111
  return
99
112
  }
100
113
 
@@ -128,7 +141,7 @@ export function useHotkeySequence(
128
141
  // Register if needed (no active registration)
129
142
  if (!registrationRef.current || !registrationRef.current.isActive) {
130
143
  registrationRef.current = managerRef.current.register(
131
- sequence,
144
+ sequenceRef.current,
132
145
  (event, context) => callbackRef.current(event, context),
133
146
  {
134
147
  ...optionsRef.current,
@@ -148,7 +161,7 @@ export function useHotkeySequence(
148
161
  registrationRef.current = null
149
162
  }
150
163
  }
151
- }, [hotkeySequenceString, mergedOptions.enabled, sequence])
164
+ }, [hotkeySequenceString, mergedOptions.enabled])
152
165
 
153
166
  // Sync callback and options on EVERY render (outside useEffect)
154
167
  if (registrationRef.current?.isActive) {
@@ -159,10 +172,3 @@ export function useHotkeySequence(
159
172
  registrationRef.current.setOptions(optionsWithoutTarget)
160
173
  }
161
174
  }
162
-
163
- /**
164
- * Type guard to check if a value is a React ref-like object.
165
- */
166
- function isRef(value: unknown): value is React.RefObject<HTMLElement | null> {
167
- return value !== null && typeof value === 'object' && 'current' in value
168
- }
@@ -0,0 +1,219 @@
1
+ import { useEffect, useRef } from 'react'
2
+ import {
3
+ detectPlatform,
4
+ formatHotkey,
5
+ getHotkeyManager,
6
+ rawHotkeyToParsedHotkey,
7
+ } from '@tanstack/hotkeys'
8
+ import { useDefaultHotkeysOptions } from './HotkeysProvider'
9
+ import { isRef } from './utils'
10
+ import type { UseHotkeyOptions } from './useHotkey'
11
+ import type {
12
+ Hotkey,
13
+ HotkeyCallback,
14
+ HotkeyRegistrationHandle,
15
+ RegisterableHotkey,
16
+ } from '@tanstack/hotkeys'
17
+
18
+ /**
19
+ * A single hotkey definition for use with `useHotkeys`.
20
+ */
21
+ export interface UseHotkeyDefinition {
22
+ /** The hotkey string (e.g., 'Mod+S', 'Escape') or RawHotkey object */
23
+ hotkey: RegisterableHotkey
24
+ /** The function to call when the hotkey is pressed */
25
+ callback: HotkeyCallback
26
+ /** Per-hotkey options (merged on top of commonOptions) */
27
+ options?: UseHotkeyOptions
28
+ }
29
+
30
+ /**
31
+ * React hook for registering multiple keyboard hotkeys at once.
32
+ *
33
+ * Uses the singleton HotkeyManager for efficient event handling.
34
+ * Accepts a dynamic array of hotkey definitions, making it safe to use
35
+ * with variable-length lists without violating the rules of hooks.
36
+ *
37
+ * Options are merged in this order:
38
+ * HotkeysProvider defaults < commonOptions < per-definition options
39
+ *
40
+ * Callbacks and options are synced on every render to avoid stale closures.
41
+ *
42
+ * @param hotkeys - Array of hotkey definitions to register
43
+ * @param commonOptions - Shared options applied to all hotkeys (overridden by per-definition options)
44
+ *
45
+ * @example
46
+ * ```tsx
47
+ * function Editor() {
48
+ * useHotkeys([
49
+ * { hotkey: 'Mod+S', callback: () => save() },
50
+ * { hotkey: 'Mod+Z', callback: () => undo() },
51
+ * { hotkey: 'Escape', callback: () => close() },
52
+ * ])
53
+ * }
54
+ * ```
55
+ *
56
+ * @example
57
+ * ```tsx
58
+ * function MenuShortcuts({ items }) {
59
+ * // Dynamic hotkeys from data -- safe because it's a single hook call
60
+ * useHotkeys(
61
+ * items.map((item) => ({
62
+ * hotkey: item.shortcut,
63
+ * callback: item.action,
64
+ * options: { enabled: item.enabled },
65
+ * })),
66
+ * { preventDefault: true },
67
+ * )
68
+ * }
69
+ * ```
70
+ */
71
+ export function useHotkeys(
72
+ hotkeys: Array<UseHotkeyDefinition>,
73
+ commonOptions: UseHotkeyOptions = {},
74
+ ): void {
75
+ type RegistrationRecord = {
76
+ handle: HotkeyRegistrationHandle
77
+ target: Document | HTMLElement | Window
78
+ }
79
+
80
+ const defaultOptions = useDefaultHotkeysOptions().hotkey
81
+ const manager = getHotkeyManager()
82
+ const platform =
83
+ commonOptions.platform ?? defaultOptions?.platform ?? detectPlatform()
84
+
85
+ const registrationsRef = useRef<Map<string, RegistrationRecord>>(new Map())
86
+ const hotkeysRef = useRef(hotkeys)
87
+ const hotkeyStringsRef = useRef<Array<Hotkey>>([])
88
+ const commonOptionsRef = useRef(commonOptions)
89
+ const defaultOptionsRef = useRef(defaultOptions)
90
+ const managerRef = useRef(manager)
91
+
92
+ const hotkeyStrings = hotkeys.map((def) =>
93
+ typeof def.hotkey === 'string'
94
+ ? def.hotkey
95
+ : (formatHotkey(rawHotkeyToParsedHotkey(def.hotkey, platform)) as Hotkey),
96
+ )
97
+
98
+ hotkeysRef.current = hotkeys
99
+ hotkeyStringsRef.current = hotkeyStrings
100
+ commonOptionsRef.current = commonOptions
101
+ defaultOptionsRef.current = defaultOptions
102
+ managerRef.current = manager
103
+
104
+ // Stable serialized keys for effect dependencies
105
+ const hotkeyKey = hotkeyStrings.join('\0')
106
+ const enabledKey = hotkeys
107
+ .map((def) => {
108
+ const merged = {
109
+ ...defaultOptions,
110
+ ...commonOptions,
111
+ ...def.options,
112
+ }
113
+ return merged.enabled ?? true
114
+ })
115
+ .join('\0')
116
+
117
+ useEffect(() => {
118
+ const prevRegistrations = registrationsRef.current
119
+ const nextRegistrations = new Map<string, RegistrationRecord>()
120
+
121
+ const rows: Array<{
122
+ registrationKey: string
123
+ def: (typeof hotkeysRef.current)[number]
124
+ hotkeyStr: Hotkey
125
+ mergedOptions: UseHotkeyOptions
126
+ resolvedTarget: Document | HTMLElement | Window
127
+ }> = []
128
+
129
+ for (let i = 0; i < hotkeysRef.current.length; i++) {
130
+ const def = hotkeysRef.current[i]!
131
+ const hotkeyStr = hotkeyStringsRef.current[i]!
132
+ const mergedOptions = {
133
+ ...defaultOptionsRef.current,
134
+ ...commonOptionsRef.current,
135
+ ...def.options,
136
+ } as UseHotkeyOptions
137
+
138
+ const resolvedTarget = isRef(mergedOptions.target)
139
+ ? mergedOptions.target.current
140
+ : (mergedOptions.target ??
141
+ (typeof document !== 'undefined' ? document : null))
142
+
143
+ if (!resolvedTarget) {
144
+ continue
145
+ }
146
+
147
+ const registrationKey = `${i}:${hotkeyStr}`
148
+ rows.push({
149
+ registrationKey,
150
+ def,
151
+ hotkeyStr,
152
+ mergedOptions,
153
+ resolvedTarget,
154
+ })
155
+ }
156
+
157
+ const nextKeys = new Set(rows.map((r) => r.registrationKey))
158
+
159
+ for (const [key, record] of prevRegistrations) {
160
+ if (!nextKeys.has(key) && record.handle.isActive) {
161
+ record.handle.unregister()
162
+ }
163
+ }
164
+
165
+ for (const row of rows) {
166
+ const { registrationKey, def, hotkeyStr, mergedOptions, resolvedTarget } =
167
+ row
168
+
169
+ const existing = prevRegistrations.get(registrationKey)
170
+ if (existing?.handle.isActive && existing.target === resolvedTarget) {
171
+ nextRegistrations.set(registrationKey, existing)
172
+ continue
173
+ }
174
+
175
+ if (existing?.handle.isActive) {
176
+ existing.handle.unregister()
177
+ }
178
+
179
+ const handle = managerRef.current.register(hotkeyStr, def.callback, {
180
+ ...mergedOptions,
181
+ target: resolvedTarget,
182
+ })
183
+ nextRegistrations.set(registrationKey, {
184
+ handle,
185
+ target: resolvedTarget,
186
+ })
187
+ }
188
+
189
+ registrationsRef.current = nextRegistrations
190
+
191
+ return () => {
192
+ for (const { handle } of registrationsRef.current.values()) {
193
+ if (handle.isActive) {
194
+ handle.unregister()
195
+ }
196
+ }
197
+ registrationsRef.current = new Map()
198
+ }
199
+ }, [hotkeyKey, enabledKey])
200
+
201
+ // Sync callbacks and options on EVERY render (outside useEffect)
202
+ for (let i = 0; i < hotkeys.length; i++) {
203
+ const def = hotkeys[i]!
204
+ const hotkeyStr = hotkeyStrings[i]!
205
+ const registrationKey = `${i}:${hotkeyStr}`
206
+ const handle = registrationsRef.current.get(registrationKey)?.handle
207
+
208
+ if (handle?.isActive) {
209
+ handle.callback = def.callback
210
+ const mergedOptions = {
211
+ ...defaultOptions,
212
+ ...commonOptions,
213
+ ...def.options,
214
+ } as UseHotkeyOptions
215
+ const { target: _target, ...optionsWithoutTarget } = mergedOptions
216
+ handle.setOptions(optionsWithoutTarget)
217
+ }
218
+ }
219
+ }
package/src/utils.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type React from 'react'
2
+
3
+ /**
4
+ * Type guard to check if a value is a React ref-like object.
5
+ */
6
+ export function isRef(
7
+ value: unknown,
8
+ ): value is React.RefObject<HTMLElement | null> {
9
+ return value !== null && typeof value === 'object' && 'current' in value
10
+ }