@tanstack/vue-hotkeys 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2,6 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_HotkeysProviderContext = require('./HotkeysProviderContext.cjs');
3
3
  const require_HotkeysProvider = require('./HotkeysProvider.cjs');
4
4
  const require_useHotkey = require('./useHotkey.cjs');
5
+ const require_useHotkeys = require('./useHotkeys.cjs');
5
6
  const require_useHeldKeys = require('./useHeldKeys.cjs');
6
7
  const require_useHeldKeyCodes = require('./useHeldKeyCodes.cjs');
7
8
  const require_useKeyHold = require('./useKeyHold.cjs');
@@ -16,6 +17,7 @@ exports.useHeldKeys = require_useHeldKeys.useHeldKeys;
16
17
  exports.useHotkey = require_useHotkey.useHotkey;
17
18
  exports.useHotkeyRecorder = require_useHotkeyRecorder.useHotkeyRecorder;
18
19
  exports.useHotkeySequence = require_useHotkeySequence.useHotkeySequence;
20
+ exports.useHotkeys = require_useHotkeys.useHotkeys;
19
21
  exports.useHotkeysContext = require_HotkeysProviderContext.useHotkeysContext;
20
22
  exports.useKeyHold = require_useKeyHold.useKeyHold;
21
23
  var _tanstack_hotkeys = require("@tanstack/hotkeys");
package/dist/index.d.cts CHANGED
@@ -2,9 +2,10 @@ import { UseHotkeyOptions, useHotkey } from "./useHotkey.cjs";
2
2
  import { UseHotkeySequenceOptions, useHotkeySequence } from "./useHotkeySequence.cjs";
3
3
  import { HotkeysProviderOptions, provideHotkeysContext, useDefaultHotkeysOptions, useHotkeysContext } from "./HotkeysProviderContext.cjs";
4
4
  import { HotkeysProvider } from "./HotkeysProvider.cjs";
5
+ import { UseHotkeyDefinition, useHotkeys } from "./useHotkeys.cjs";
5
6
  import { useHeldKeys } from "./useHeldKeys.cjs";
6
7
  import { useHeldKeyCodes } from "./useHeldKeyCodes.cjs";
7
8
  import { useKeyHold } from "./useKeyHold.cjs";
8
9
  import { VueHotkeyRecorder, useHotkeyRecorder } from "./useHotkeyRecorder.cjs";
9
10
  export * from "@tanstack/hotkeys";
10
- export { HotkeysProvider, HotkeysProviderOptions, UseHotkeyOptions, UseHotkeySequenceOptions, VueHotkeyRecorder, provideHotkeysContext, useDefaultHotkeysOptions, useHeldKeyCodes, useHeldKeys, useHotkey, useHotkeyRecorder, useHotkeySequence, useHotkeysContext, useKeyHold };
11
+ export { HotkeysProvider, HotkeysProviderOptions, UseHotkeyDefinition, UseHotkeyOptions, UseHotkeySequenceOptions, VueHotkeyRecorder, provideHotkeysContext, useDefaultHotkeysOptions, useHeldKeyCodes, useHeldKeys, useHotkey, useHotkeyRecorder, useHotkeySequence, useHotkeys, useHotkeysContext, useKeyHold };
package/dist/index.d.ts CHANGED
@@ -2,9 +2,10 @@ import { UseHotkeyOptions, useHotkey } from "./useHotkey.js";
2
2
  import { UseHotkeySequenceOptions, useHotkeySequence } from "./useHotkeySequence.js";
3
3
  import { HotkeysProviderOptions, provideHotkeysContext, useDefaultHotkeysOptions, useHotkeysContext } from "./HotkeysProviderContext.js";
4
4
  import { HotkeysProvider } from "./HotkeysProvider.js";
5
+ import { UseHotkeyDefinition, useHotkeys } from "./useHotkeys.js";
5
6
  import { useHeldKeys } from "./useHeldKeys.js";
6
7
  import { useHeldKeyCodes } from "./useHeldKeyCodes.js";
7
8
  import { useKeyHold } from "./useKeyHold.js";
8
9
  import { VueHotkeyRecorder, useHotkeyRecorder } from "./useHotkeyRecorder.js";
9
10
  export * from "@tanstack/hotkeys";
10
- export { HotkeysProvider, HotkeysProviderOptions, UseHotkeyOptions, UseHotkeySequenceOptions, VueHotkeyRecorder, provideHotkeysContext, useDefaultHotkeysOptions, useHeldKeyCodes, useHeldKeys, useHotkey, useHotkeyRecorder, useHotkeySequence, useHotkeysContext, useKeyHold };
11
+ export { HotkeysProvider, HotkeysProviderOptions, UseHotkeyDefinition, UseHotkeyOptions, UseHotkeySequenceOptions, VueHotkeyRecorder, provideHotkeysContext, useDefaultHotkeysOptions, useHeldKeyCodes, useHeldKeys, useHotkey, useHotkeyRecorder, useHotkeySequence, useHotkeys, useHotkeysContext, useKeyHold };
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { provideHotkeysContext, useDefaultHotkeysOptions, useHotkeysContext } from "./HotkeysProviderContext.js";
2
2
  import { HotkeysProvider } from "./HotkeysProvider.js";
3
3
  import { useHotkey } from "./useHotkey.js";
4
+ import { useHotkeys } from "./useHotkeys.js";
4
5
  import { useHeldKeys } from "./useHeldKeys.js";
5
6
  import { useHeldKeyCodes } from "./useHeldKeyCodes.js";
6
7
  import { useKeyHold } from "./useKeyHold.js";
@@ -9,4 +10,4 @@ import { useHotkeyRecorder } from "./useHotkeyRecorder.js";
9
10
 
10
11
  export * from "@tanstack/hotkeys"
11
12
 
12
- export { HotkeysProvider, provideHotkeysContext, useDefaultHotkeysOptions, useHeldKeyCodes, useHeldKeys, useHotkey, useHotkeyRecorder, useHotkeySequence, useHotkeysContext, useKeyHold };
13
+ export { HotkeysProvider, provideHotkeysContext, useDefaultHotkeysOptions, useHeldKeyCodes, useHeldKeys, useHotkey, useHotkeyRecorder, useHotkeySequence, useHotkeys, useHotkeysContext, useKeyHold };
@@ -0,0 +1,140 @@
1
+ const require_HotkeysProviderContext = require('./HotkeysProviderContext.cjs');
2
+ let _tanstack_hotkeys = require("@tanstack/hotkeys");
3
+ let vue = require("vue");
4
+
5
+ //#region src/useHotkeys.ts
6
+ /**
7
+ * Vue composable for registering multiple keyboard hotkeys at once.
8
+ *
9
+ * Uses the singleton HotkeyManager for efficient event handling.
10
+ * Accepts a dynamic array of hotkey definitions, making it safe to use
11
+ * with variable-length lists.
12
+ *
13
+ * Options are merged in this order:
14
+ * HotkeysProvider defaults < commonOptions < per-definition options
15
+ *
16
+ * @param hotkeys - Array of hotkey definitions to register, or a getter/ref
17
+ * @param commonOptions - Shared options applied to all hotkeys (overridden by per-definition options)
18
+ *
19
+ * @example
20
+ * ```vue
21
+ * <script setup>
22
+ * import { useHotkeys } from '@tanstack/vue-hotkeys'
23
+ *
24
+ * useHotkeys([
25
+ * { hotkey: 'Mod+S', callback: () => save() },
26
+ * { hotkey: 'Mod+Z', callback: () => undo() },
27
+ * { hotkey: 'Escape', callback: () => close() },
28
+ * ])
29
+ * <\/script>
30
+ * ```
31
+ *
32
+ * @example
33
+ * ```vue
34
+ * <script setup>
35
+ * import { computed } from 'vue'
36
+ * import { useHotkeys } from '@tanstack/vue-hotkeys'
37
+ *
38
+ * const items = computed(() => [...])
39
+ * // Dynamic hotkeys from reactive data
40
+ * useHotkeys(
41
+ * () => items.value.map((item) => ({
42
+ * hotkey: item.shortcut,
43
+ * callback: item.action,
44
+ * options: { enabled: item.enabled },
45
+ * })),
46
+ * { preventDefault: true },
47
+ * )
48
+ * <\/script>
49
+ * ```
50
+ */
51
+ function useHotkeys(hotkeys, commonOptions = {}) {
52
+ const defaultOptions = require_HotkeysProviderContext.useDefaultHotkeysOptions();
53
+ const manager = (0, _tanstack_hotkeys.getHotkeyManager)();
54
+ const registrations = /* @__PURE__ */ new Map();
55
+ const stopWatcher = (0, vue.watch)(() => {
56
+ const resolvedHotkeys = resolveMaybeRefOrGetter(hotkeys);
57
+ const resolvedCommonOptions = resolveMaybeRefOrGetter(commonOptions);
58
+ return resolvedHotkeys.map((def, i) => {
59
+ const resolvedHotkey = resolveMaybeRefOrGetter(def.hotkey);
60
+ const resolvedDefOptions = def.options ? resolveMaybeRefOrGetter(def.options) : {};
61
+ const mergedOptions = {
62
+ ...defaultOptions.hotkey,
63
+ ...resolvedCommonOptions,
64
+ ...resolvedDefOptions
65
+ };
66
+ const platform = mergedOptions.platform ?? (0, _tanstack_hotkeys.detectPlatform)();
67
+ const hotkeyString = typeof resolvedHotkey === "string" ? resolvedHotkey : (0, _tanstack_hotkeys.formatHotkey)((0, _tanstack_hotkeys.rawHotkeyToParsedHotkey)(resolvedHotkey, platform));
68
+ const resolvedEnabled = mergedOptions.enabled === void 0 ? void 0 : resolveMaybeRefOrGetter(mergedOptions.enabled);
69
+ const resolvedTarget = mergedOptions.target === void 0 ? void 0 : resolveMaybeRefOrGetter(mergedOptions.target);
70
+ return {
71
+ index: i,
72
+ hotkeyString,
73
+ callback: def.callback,
74
+ mergedOptions,
75
+ resolvedEnabled,
76
+ resolvedTarget
77
+ };
78
+ });
79
+ }, (resolved) => {
80
+ const nextKeys = /* @__PURE__ */ new Set();
81
+ const prepared = [];
82
+ for (const entry of resolved) {
83
+ const finalTarget = entry.resolvedTarget ?? (typeof document !== "undefined" ? document : null);
84
+ if (!finalTarget) continue;
85
+ const registrationKey = `${entry.index}:${entry.hotkeyString}`;
86
+ nextKeys.add(registrationKey);
87
+ prepared.push({
88
+ registrationKey,
89
+ entry,
90
+ finalTarget
91
+ });
92
+ }
93
+ for (const [key, record] of [...registrations.entries()]) if (!nextKeys.has(key)) {
94
+ if (record.handle.isActive) record.handle.unregister();
95
+ registrations.delete(key);
96
+ }
97
+ for (const { registrationKey, entry, finalTarget } of prepared) {
98
+ const existing = registrations.get(registrationKey);
99
+ if (existing?.handle.isActive && existing.target === finalTarget) {
100
+ existing.handle.callback = entry.callback;
101
+ const { target: _target, enabled: _enabled, ...restOptions } = entry.mergedOptions;
102
+ const optionsWithoutTarget = {
103
+ ...restOptions,
104
+ ...entry.resolvedEnabled === void 0 ? {} : { enabled: entry.resolvedEnabled }
105
+ };
106
+ existing.handle.setOptions(optionsWithoutTarget);
107
+ continue;
108
+ }
109
+ if (existing) {
110
+ if (existing.handle.isActive) existing.handle.unregister();
111
+ registrations.delete(registrationKey);
112
+ }
113
+ const { target: _target, enabled: _enabled, ...restOptions } = entry.mergedOptions;
114
+ const optionsWithoutTarget = {
115
+ ...restOptions,
116
+ ...entry.resolvedEnabled === void 0 ? {} : { enabled: entry.resolvedEnabled }
117
+ };
118
+ const handle = manager.register(entry.hotkeyString, entry.callback, {
119
+ ...optionsWithoutTarget,
120
+ target: finalTarget
121
+ });
122
+ registrations.set(registrationKey, {
123
+ handle,
124
+ target: finalTarget
125
+ });
126
+ }
127
+ }, { immediate: true });
128
+ (0, vue.onUnmounted)(() => {
129
+ stopWatcher();
130
+ for (const { handle } of registrations.values()) if (handle.isActive) handle.unregister();
131
+ registrations.clear();
132
+ });
133
+ }
134
+ function resolveMaybeRefOrGetter(value) {
135
+ return typeof value === "function" ? value() : (0, vue.unref)(value);
136
+ }
137
+
138
+ //#endregion
139
+ exports.useHotkeys = useHotkeys;
140
+ //# sourceMappingURL=useHotkeys.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useHotkeys.cjs","names":["useDefaultHotkeysOptions"],"sources":["../src/useHotkeys.ts"],"sourcesContent":["import { onUnmounted, unref, watch } from 'vue'\nimport {\n detectPlatform,\n formatHotkey,\n getHotkeyManager,\n rawHotkeyToParsedHotkey,\n} from '@tanstack/hotkeys'\nimport { useDefaultHotkeysOptions } from './HotkeysProviderContext'\nimport type { UseHotkeyOptions } from './useHotkey'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyRegistrationHandle,\n RegisterableHotkey,\n} from '@tanstack/hotkeys'\nimport type { MaybeRefOrGetter } from 'vue'\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: MaybeRefOrGetter<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?: MaybeRefOrGetter<UseHotkeyOptions>\n}\n\n/**\n * Vue composable 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.\n *\n * Options are merged in this order:\n * HotkeysProvider defaults < commonOptions < per-definition options\n *\n * @param hotkeys - Array of hotkey definitions to register, or a getter/ref\n * @param commonOptions - Shared options applied to all hotkeys (overridden by per-definition options)\n *\n * @example\n * ```vue\n * <script setup>\n * import { useHotkeys } from '@tanstack/vue-hotkeys'\n *\n * useHotkeys([\n * { hotkey: 'Mod+S', callback: () => save() },\n * { hotkey: 'Mod+Z', callback: () => undo() },\n * { hotkey: 'Escape', callback: () => close() },\n * ])\n * </script>\n * ```\n *\n * @example\n * ```vue\n * <script setup>\n * import { computed } from 'vue'\n * import { useHotkeys } from '@tanstack/vue-hotkeys'\n *\n * const items = computed(() => [...])\n * // Dynamic hotkeys from reactive data\n * useHotkeys(\n * () => items.value.map((item) => ({\n * hotkey: item.shortcut,\n * callback: item.action,\n * options: { enabled: item.enabled },\n * })),\n * { preventDefault: true },\n * )\n * </script>\n * ```\n */\nexport function useHotkeys(\n hotkeys: MaybeRefOrGetter<Array<UseHotkeyDefinition>>,\n commonOptions: MaybeRefOrGetter<UseHotkeyOptions> = {},\n): void {\n type RegistrationRecord = {\n handle: HotkeyRegistrationHandle\n target: Document | HTMLElement | Window\n }\n\n const defaultOptions = useDefaultHotkeysOptions()\n const manager = getHotkeyManager()\n\n const registrations = new Map<string, RegistrationRecord>()\n\n const stopWatcher = watch(\n () => {\n const resolvedHotkeys = resolveMaybeRefOrGetter(hotkeys)\n const resolvedCommonOptions = resolveMaybeRefOrGetter(commonOptions)\n\n return resolvedHotkeys.map((def, i) => {\n const resolvedHotkey = resolveMaybeRefOrGetter(def.hotkey)\n const resolvedDefOptions = def.options\n ? resolveMaybeRefOrGetter(def.options)\n : {}\n\n const mergedOptions = {\n ...defaultOptions.hotkey,\n ...resolvedCommonOptions,\n ...resolvedDefOptions,\n } as UseHotkeyOptions\n\n const platform = mergedOptions.platform ?? detectPlatform()\n const hotkeyString: Hotkey =\n typeof resolvedHotkey === 'string'\n ? resolvedHotkey\n : (formatHotkey(\n rawHotkeyToParsedHotkey(resolvedHotkey as any, platform),\n ) as Hotkey)\n\n const resolvedEnabled =\n mergedOptions.enabled === undefined\n ? undefined\n : resolveMaybeRefOrGetter(mergedOptions.enabled)\n const resolvedTarget =\n mergedOptions.target === undefined\n ? undefined\n : resolveMaybeRefOrGetter(mergedOptions.target as any)\n\n return {\n index: i,\n hotkeyString,\n callback: def.callback,\n mergedOptions,\n resolvedEnabled,\n resolvedTarget,\n }\n })\n },\n (resolved) => {\n const nextKeys = new Set<string>()\n const prepared: Array<{\n registrationKey: string\n entry: (typeof resolved)[number]\n finalTarget: Document | HTMLElement | Window\n }> = []\n\n for (const entry of resolved) {\n const finalTarget =\n entry.resolvedTarget ??\n (typeof document !== 'undefined' ? document : null)\n\n if (!finalTarget) {\n continue\n }\n\n const registrationKey = `${entry.index}:${entry.hotkeyString}`\n nextKeys.add(registrationKey)\n prepared.push({ registrationKey, entry, finalTarget })\n }\n\n for (const [key, record] of [...registrations.entries()]) {\n if (!nextKeys.has(key)) {\n if (record.handle.isActive) {\n record.handle.unregister()\n }\n registrations.delete(key)\n }\n }\n\n for (const { registrationKey, entry, finalTarget } of prepared) {\n const existing = registrations.get(registrationKey)\n if (existing?.handle.isActive && existing.target === finalTarget) {\n existing.handle.callback = entry.callback\n const {\n target: _target,\n enabled: _enabled,\n ...restOptions\n } = entry.mergedOptions\n const optionsWithoutTarget = {\n ...restOptions,\n ...(entry.resolvedEnabled === undefined\n ? {}\n : { enabled: entry.resolvedEnabled }),\n }\n existing.handle.setOptions(optionsWithoutTarget)\n continue\n }\n\n if (existing) {\n if (existing.handle.isActive) {\n existing.handle.unregister()\n }\n registrations.delete(registrationKey)\n }\n\n const {\n target: _target,\n enabled: _enabled,\n ...restOptions\n } = entry.mergedOptions\n const optionsWithoutTarget = {\n ...restOptions,\n ...(entry.resolvedEnabled === undefined\n ? {}\n : { enabled: entry.resolvedEnabled }),\n }\n\n const handle = manager.register(entry.hotkeyString, entry.callback, {\n ...optionsWithoutTarget,\n target: finalTarget,\n })\n registrations.set(registrationKey, { handle, target: finalTarget })\n }\n },\n { immediate: true },\n )\n\n onUnmounted(() => {\n stopWatcher()\n for (const { handle } of registrations.values()) {\n if (handle.isActive) {\n handle.unregister()\n }\n }\n registrations.clear()\n })\n}\n\nfunction resolveMaybeRefOrGetter<T>(value: MaybeRefOrGetter<T>): T {\n return typeof value === 'function' ? (value as () => T)() : unref(value)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,SAAgB,WACd,SACA,gBAAoD,EAAE,EAChD;CAMN,MAAM,iBAAiBA,yDAA0B;CACjD,MAAM,mDAA4B;CAElC,MAAM,gCAAgB,IAAI,KAAiC;CAE3D,MAAM,mCACE;EACJ,MAAM,kBAAkB,wBAAwB,QAAQ;EACxD,MAAM,wBAAwB,wBAAwB,cAAc;AAEpE,SAAO,gBAAgB,KAAK,KAAK,MAAM;GACrC,MAAM,iBAAiB,wBAAwB,IAAI,OAAO;GAC1D,MAAM,qBAAqB,IAAI,UAC3B,wBAAwB,IAAI,QAAQ,GACpC,EAAE;GAEN,MAAM,gBAAgB;IACpB,GAAG,eAAe;IAClB,GAAG;IACH,GAAG;IACJ;GAED,MAAM,WAAW,cAAc,mDAA4B;GAC3D,MAAM,eACJ,OAAO,mBAAmB,WACtB,oGAE0B,gBAAuB,SAAS,CACzD;GAEP,MAAM,kBACJ,cAAc,YAAY,SACtB,SACA,wBAAwB,cAAc,QAAQ;GACpD,MAAM,iBACJ,cAAc,WAAW,SACrB,SACA,wBAAwB,cAAc,OAAc;AAE1D,UAAO;IACL,OAAO;IACP;IACA,UAAU,IAAI;IACd;IACA;IACA;IACD;IACD;KAEH,aAAa;EACZ,MAAM,2BAAW,IAAI,KAAa;EAClC,MAAM,WAID,EAAE;AAEP,OAAK,MAAM,SAAS,UAAU;GAC5B,MAAM,cACJ,MAAM,mBACL,OAAO,aAAa,cAAc,WAAW;AAEhD,OAAI,CAAC,YACH;GAGF,MAAM,kBAAkB,GAAG,MAAM,MAAM,GAAG,MAAM;AAChD,YAAS,IAAI,gBAAgB;AAC7B,YAAS,KAAK;IAAE;IAAiB;IAAO;IAAa,CAAC;;AAGxD,OAAK,MAAM,CAAC,KAAK,WAAW,CAAC,GAAG,cAAc,SAAS,CAAC,CACtD,KAAI,CAAC,SAAS,IAAI,IAAI,EAAE;AACtB,OAAI,OAAO,OAAO,SAChB,QAAO,OAAO,YAAY;AAE5B,iBAAc,OAAO,IAAI;;AAI7B,OAAK,MAAM,EAAE,iBAAiB,OAAO,iBAAiB,UAAU;GAC9D,MAAM,WAAW,cAAc,IAAI,gBAAgB;AACnD,OAAI,UAAU,OAAO,YAAY,SAAS,WAAW,aAAa;AAChE,aAAS,OAAO,WAAW,MAAM;IACjC,MAAM,EACJ,QAAQ,SACR,SAAS,UACT,GAAG,gBACD,MAAM;IACV,MAAM,uBAAuB;KAC3B,GAAG;KACH,GAAI,MAAM,oBAAoB,SAC1B,EAAE,GACF,EAAE,SAAS,MAAM,iBAAiB;KACvC;AACD,aAAS,OAAO,WAAW,qBAAqB;AAChD;;AAGF,OAAI,UAAU;AACZ,QAAI,SAAS,OAAO,SAClB,UAAS,OAAO,YAAY;AAE9B,kBAAc,OAAO,gBAAgB;;GAGvC,MAAM,EACJ,QAAQ,SACR,SAAS,UACT,GAAG,gBACD,MAAM;GACV,MAAM,uBAAuB;IAC3B,GAAG;IACH,GAAI,MAAM,oBAAoB,SAC1B,EAAE,GACF,EAAE,SAAS,MAAM,iBAAiB;IACvC;GAED,MAAM,SAAS,QAAQ,SAAS,MAAM,cAAc,MAAM,UAAU;IAClE,GAAG;IACH,QAAQ;IACT,CAAC;AACF,iBAAc,IAAI,iBAAiB;IAAE;IAAQ,QAAQ;IAAa,CAAC;;IAGvE,EAAE,WAAW,MAAM,CACpB;AAED,4BAAkB;AAChB,eAAa;AACb,OAAK,MAAM,EAAE,YAAY,cAAc,QAAQ,CAC7C,KAAI,OAAO,SACT,QAAO,YAAY;AAGvB,gBAAc,OAAO;GACrB;;AAGJ,SAAS,wBAA2B,OAA+B;AACjE,QAAO,OAAO,UAAU,aAAc,OAAmB,kBAAS,MAAM"}
@@ -0,0 +1,65 @@
1
+ import { UseHotkeyOptions } from "./useHotkey.cjs";
2
+ import { HotkeyCallback, RegisterableHotkey } from "@tanstack/hotkeys";
3
+ import { MaybeRefOrGetter } from "vue";
4
+
5
+ //#region src/useHotkeys.d.ts
6
+ /**
7
+ * A single hotkey definition for use with `useHotkeys`.
8
+ */
9
+ interface UseHotkeyDefinition {
10
+ /** The hotkey string (e.g., 'Mod+S', 'Escape') or RawHotkey object */
11
+ hotkey: MaybeRefOrGetter<RegisterableHotkey>;
12
+ /** The function to call when the hotkey is pressed */
13
+ callback: HotkeyCallback;
14
+ /** Per-hotkey options (merged on top of commonOptions) */
15
+ options?: MaybeRefOrGetter<UseHotkeyOptions>;
16
+ }
17
+ /**
18
+ * Vue composable for registering multiple keyboard hotkeys at once.
19
+ *
20
+ * Uses the singleton HotkeyManager for efficient event handling.
21
+ * Accepts a dynamic array of hotkey definitions, making it safe to use
22
+ * with variable-length lists.
23
+ *
24
+ * Options are merged in this order:
25
+ * HotkeysProvider defaults < commonOptions < per-definition options
26
+ *
27
+ * @param hotkeys - Array of hotkey definitions to register, or a getter/ref
28
+ * @param commonOptions - Shared options applied to all hotkeys (overridden by per-definition options)
29
+ *
30
+ * @example
31
+ * ```vue
32
+ * <script setup>
33
+ * import { useHotkeys } from '@tanstack/vue-hotkeys'
34
+ *
35
+ * useHotkeys([
36
+ * { hotkey: 'Mod+S', callback: () => save() },
37
+ * { hotkey: 'Mod+Z', callback: () => undo() },
38
+ * { hotkey: 'Escape', callback: () => close() },
39
+ * ])
40
+ * </script>
41
+ * ```
42
+ *
43
+ * @example
44
+ * ```vue
45
+ * <script setup>
46
+ * import { computed } from 'vue'
47
+ * import { useHotkeys } from '@tanstack/vue-hotkeys'
48
+ *
49
+ * const items = computed(() => [...])
50
+ * // Dynamic hotkeys from reactive data
51
+ * useHotkeys(
52
+ * () => items.value.map((item) => ({
53
+ * hotkey: item.shortcut,
54
+ * callback: item.action,
55
+ * options: { enabled: item.enabled },
56
+ * })),
57
+ * { preventDefault: true },
58
+ * )
59
+ * </script>
60
+ * ```
61
+ */
62
+ declare function useHotkeys(hotkeys: MaybeRefOrGetter<Array<UseHotkeyDefinition>>, commonOptions?: MaybeRefOrGetter<UseHotkeyOptions>): void;
63
+ //#endregion
64
+ export { UseHotkeyDefinition, useHotkeys };
65
+ //# sourceMappingURL=useHotkeys.d.cts.map
@@ -0,0 +1,65 @@
1
+ import { UseHotkeyOptions } from "./useHotkey.js";
2
+ import { HotkeyCallback, RegisterableHotkey } from "@tanstack/hotkeys";
3
+ import { MaybeRefOrGetter } from "vue";
4
+
5
+ //#region src/useHotkeys.d.ts
6
+ /**
7
+ * A single hotkey definition for use with `useHotkeys`.
8
+ */
9
+ interface UseHotkeyDefinition {
10
+ /** The hotkey string (e.g., 'Mod+S', 'Escape') or RawHotkey object */
11
+ hotkey: MaybeRefOrGetter<RegisterableHotkey>;
12
+ /** The function to call when the hotkey is pressed */
13
+ callback: HotkeyCallback;
14
+ /** Per-hotkey options (merged on top of commonOptions) */
15
+ options?: MaybeRefOrGetter<UseHotkeyOptions>;
16
+ }
17
+ /**
18
+ * Vue composable for registering multiple keyboard hotkeys at once.
19
+ *
20
+ * Uses the singleton HotkeyManager for efficient event handling.
21
+ * Accepts a dynamic array of hotkey definitions, making it safe to use
22
+ * with variable-length lists.
23
+ *
24
+ * Options are merged in this order:
25
+ * HotkeysProvider defaults < commonOptions < per-definition options
26
+ *
27
+ * @param hotkeys - Array of hotkey definitions to register, or a getter/ref
28
+ * @param commonOptions - Shared options applied to all hotkeys (overridden by per-definition options)
29
+ *
30
+ * @example
31
+ * ```vue
32
+ * <script setup>
33
+ * import { useHotkeys } from '@tanstack/vue-hotkeys'
34
+ *
35
+ * useHotkeys([
36
+ * { hotkey: 'Mod+S', callback: () => save() },
37
+ * { hotkey: 'Mod+Z', callback: () => undo() },
38
+ * { hotkey: 'Escape', callback: () => close() },
39
+ * ])
40
+ * </script>
41
+ * ```
42
+ *
43
+ * @example
44
+ * ```vue
45
+ * <script setup>
46
+ * import { computed } from 'vue'
47
+ * import { useHotkeys } from '@tanstack/vue-hotkeys'
48
+ *
49
+ * const items = computed(() => [...])
50
+ * // Dynamic hotkeys from reactive data
51
+ * useHotkeys(
52
+ * () => items.value.map((item) => ({
53
+ * hotkey: item.shortcut,
54
+ * callback: item.action,
55
+ * options: { enabled: item.enabled },
56
+ * })),
57
+ * { preventDefault: true },
58
+ * )
59
+ * </script>
60
+ * ```
61
+ */
62
+ declare function useHotkeys(hotkeys: MaybeRefOrGetter<Array<UseHotkeyDefinition>>, commonOptions?: MaybeRefOrGetter<UseHotkeyOptions>): void;
63
+ //#endregion
64
+ export { UseHotkeyDefinition, useHotkeys };
65
+ //# sourceMappingURL=useHotkeys.d.ts.map
@@ -0,0 +1,140 @@
1
+ import { useDefaultHotkeysOptions } from "./HotkeysProviderContext.js";
2
+ import { detectPlatform, formatHotkey, getHotkeyManager, rawHotkeyToParsedHotkey } from "@tanstack/hotkeys";
3
+ import { onUnmounted, unref, watch } from "vue";
4
+
5
+ //#region src/useHotkeys.ts
6
+ /**
7
+ * Vue composable for registering multiple keyboard hotkeys at once.
8
+ *
9
+ * Uses the singleton HotkeyManager for efficient event handling.
10
+ * Accepts a dynamic array of hotkey definitions, making it safe to use
11
+ * with variable-length lists.
12
+ *
13
+ * Options are merged in this order:
14
+ * HotkeysProvider defaults < commonOptions < per-definition options
15
+ *
16
+ * @param hotkeys - Array of hotkey definitions to register, or a getter/ref
17
+ * @param commonOptions - Shared options applied to all hotkeys (overridden by per-definition options)
18
+ *
19
+ * @example
20
+ * ```vue
21
+ * <script setup>
22
+ * import { useHotkeys } from '@tanstack/vue-hotkeys'
23
+ *
24
+ * useHotkeys([
25
+ * { hotkey: 'Mod+S', callback: () => save() },
26
+ * { hotkey: 'Mod+Z', callback: () => undo() },
27
+ * { hotkey: 'Escape', callback: () => close() },
28
+ * ])
29
+ * <\/script>
30
+ * ```
31
+ *
32
+ * @example
33
+ * ```vue
34
+ * <script setup>
35
+ * import { computed } from 'vue'
36
+ * import { useHotkeys } from '@tanstack/vue-hotkeys'
37
+ *
38
+ * const items = computed(() => [...])
39
+ * // Dynamic hotkeys from reactive data
40
+ * useHotkeys(
41
+ * () => items.value.map((item) => ({
42
+ * hotkey: item.shortcut,
43
+ * callback: item.action,
44
+ * options: { enabled: item.enabled },
45
+ * })),
46
+ * { preventDefault: true },
47
+ * )
48
+ * <\/script>
49
+ * ```
50
+ */
51
+ function useHotkeys(hotkeys, commonOptions = {}) {
52
+ const defaultOptions = useDefaultHotkeysOptions();
53
+ const manager = getHotkeyManager();
54
+ const registrations = /* @__PURE__ */ new Map();
55
+ const stopWatcher = watch(() => {
56
+ const resolvedHotkeys = resolveMaybeRefOrGetter(hotkeys);
57
+ const resolvedCommonOptions = resolveMaybeRefOrGetter(commonOptions);
58
+ return resolvedHotkeys.map((def, i) => {
59
+ const resolvedHotkey = resolveMaybeRefOrGetter(def.hotkey);
60
+ const resolvedDefOptions = def.options ? resolveMaybeRefOrGetter(def.options) : {};
61
+ const mergedOptions = {
62
+ ...defaultOptions.hotkey,
63
+ ...resolvedCommonOptions,
64
+ ...resolvedDefOptions
65
+ };
66
+ const platform = mergedOptions.platform ?? detectPlatform();
67
+ const hotkeyString = typeof resolvedHotkey === "string" ? resolvedHotkey : formatHotkey(rawHotkeyToParsedHotkey(resolvedHotkey, platform));
68
+ const resolvedEnabled = mergedOptions.enabled === void 0 ? void 0 : resolveMaybeRefOrGetter(mergedOptions.enabled);
69
+ const resolvedTarget = mergedOptions.target === void 0 ? void 0 : resolveMaybeRefOrGetter(mergedOptions.target);
70
+ return {
71
+ index: i,
72
+ hotkeyString,
73
+ callback: def.callback,
74
+ mergedOptions,
75
+ resolvedEnabled,
76
+ resolvedTarget
77
+ };
78
+ });
79
+ }, (resolved) => {
80
+ const nextKeys = /* @__PURE__ */ new Set();
81
+ const prepared = [];
82
+ for (const entry of resolved) {
83
+ const finalTarget = entry.resolvedTarget ?? (typeof document !== "undefined" ? document : null);
84
+ if (!finalTarget) continue;
85
+ const registrationKey = `${entry.index}:${entry.hotkeyString}`;
86
+ nextKeys.add(registrationKey);
87
+ prepared.push({
88
+ registrationKey,
89
+ entry,
90
+ finalTarget
91
+ });
92
+ }
93
+ for (const [key, record] of [...registrations.entries()]) if (!nextKeys.has(key)) {
94
+ if (record.handle.isActive) record.handle.unregister();
95
+ registrations.delete(key);
96
+ }
97
+ for (const { registrationKey, entry, finalTarget } of prepared) {
98
+ const existing = registrations.get(registrationKey);
99
+ if (existing?.handle.isActive && existing.target === finalTarget) {
100
+ existing.handle.callback = entry.callback;
101
+ const { target: _target, enabled: _enabled, ...restOptions } = entry.mergedOptions;
102
+ const optionsWithoutTarget = {
103
+ ...restOptions,
104
+ ...entry.resolvedEnabled === void 0 ? {} : { enabled: entry.resolvedEnabled }
105
+ };
106
+ existing.handle.setOptions(optionsWithoutTarget);
107
+ continue;
108
+ }
109
+ if (existing) {
110
+ if (existing.handle.isActive) existing.handle.unregister();
111
+ registrations.delete(registrationKey);
112
+ }
113
+ const { target: _target, enabled: _enabled, ...restOptions } = entry.mergedOptions;
114
+ const optionsWithoutTarget = {
115
+ ...restOptions,
116
+ ...entry.resolvedEnabled === void 0 ? {} : { enabled: entry.resolvedEnabled }
117
+ };
118
+ const handle = manager.register(entry.hotkeyString, entry.callback, {
119
+ ...optionsWithoutTarget,
120
+ target: finalTarget
121
+ });
122
+ registrations.set(registrationKey, {
123
+ handle,
124
+ target: finalTarget
125
+ });
126
+ }
127
+ }, { immediate: true });
128
+ onUnmounted(() => {
129
+ stopWatcher();
130
+ for (const { handle } of registrations.values()) if (handle.isActive) handle.unregister();
131
+ registrations.clear();
132
+ });
133
+ }
134
+ function resolveMaybeRefOrGetter(value) {
135
+ return typeof value === "function" ? value() : unref(value);
136
+ }
137
+
138
+ //#endregion
139
+ export { useHotkeys };
140
+ //# sourceMappingURL=useHotkeys.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useHotkeys.js","names":[],"sources":["../src/useHotkeys.ts"],"sourcesContent":["import { onUnmounted, unref, watch } from 'vue'\nimport {\n detectPlatform,\n formatHotkey,\n getHotkeyManager,\n rawHotkeyToParsedHotkey,\n} from '@tanstack/hotkeys'\nimport { useDefaultHotkeysOptions } from './HotkeysProviderContext'\nimport type { UseHotkeyOptions } from './useHotkey'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyRegistrationHandle,\n RegisterableHotkey,\n} from '@tanstack/hotkeys'\nimport type { MaybeRefOrGetter } from 'vue'\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: MaybeRefOrGetter<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?: MaybeRefOrGetter<UseHotkeyOptions>\n}\n\n/**\n * Vue composable 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.\n *\n * Options are merged in this order:\n * HotkeysProvider defaults < commonOptions < per-definition options\n *\n * @param hotkeys - Array of hotkey definitions to register, or a getter/ref\n * @param commonOptions - Shared options applied to all hotkeys (overridden by per-definition options)\n *\n * @example\n * ```vue\n * <script setup>\n * import { useHotkeys } from '@tanstack/vue-hotkeys'\n *\n * useHotkeys([\n * { hotkey: 'Mod+S', callback: () => save() },\n * { hotkey: 'Mod+Z', callback: () => undo() },\n * { hotkey: 'Escape', callback: () => close() },\n * ])\n * </script>\n * ```\n *\n * @example\n * ```vue\n * <script setup>\n * import { computed } from 'vue'\n * import { useHotkeys } from '@tanstack/vue-hotkeys'\n *\n * const items = computed(() => [...])\n * // Dynamic hotkeys from reactive data\n * useHotkeys(\n * () => items.value.map((item) => ({\n * hotkey: item.shortcut,\n * callback: item.action,\n * options: { enabled: item.enabled },\n * })),\n * { preventDefault: true },\n * )\n * </script>\n * ```\n */\nexport function useHotkeys(\n hotkeys: MaybeRefOrGetter<Array<UseHotkeyDefinition>>,\n commonOptions: MaybeRefOrGetter<UseHotkeyOptions> = {},\n): void {\n type RegistrationRecord = {\n handle: HotkeyRegistrationHandle\n target: Document | HTMLElement | Window\n }\n\n const defaultOptions = useDefaultHotkeysOptions()\n const manager = getHotkeyManager()\n\n const registrations = new Map<string, RegistrationRecord>()\n\n const stopWatcher = watch(\n () => {\n const resolvedHotkeys = resolveMaybeRefOrGetter(hotkeys)\n const resolvedCommonOptions = resolveMaybeRefOrGetter(commonOptions)\n\n return resolvedHotkeys.map((def, i) => {\n const resolvedHotkey = resolveMaybeRefOrGetter(def.hotkey)\n const resolvedDefOptions = def.options\n ? resolveMaybeRefOrGetter(def.options)\n : {}\n\n const mergedOptions = {\n ...defaultOptions.hotkey,\n ...resolvedCommonOptions,\n ...resolvedDefOptions,\n } as UseHotkeyOptions\n\n const platform = mergedOptions.platform ?? detectPlatform()\n const hotkeyString: Hotkey =\n typeof resolvedHotkey === 'string'\n ? resolvedHotkey\n : (formatHotkey(\n rawHotkeyToParsedHotkey(resolvedHotkey as any, platform),\n ) as Hotkey)\n\n const resolvedEnabled =\n mergedOptions.enabled === undefined\n ? undefined\n : resolveMaybeRefOrGetter(mergedOptions.enabled)\n const resolvedTarget =\n mergedOptions.target === undefined\n ? undefined\n : resolveMaybeRefOrGetter(mergedOptions.target as any)\n\n return {\n index: i,\n hotkeyString,\n callback: def.callback,\n mergedOptions,\n resolvedEnabled,\n resolvedTarget,\n }\n })\n },\n (resolved) => {\n const nextKeys = new Set<string>()\n const prepared: Array<{\n registrationKey: string\n entry: (typeof resolved)[number]\n finalTarget: Document | HTMLElement | Window\n }> = []\n\n for (const entry of resolved) {\n const finalTarget =\n entry.resolvedTarget ??\n (typeof document !== 'undefined' ? document : null)\n\n if (!finalTarget) {\n continue\n }\n\n const registrationKey = `${entry.index}:${entry.hotkeyString}`\n nextKeys.add(registrationKey)\n prepared.push({ registrationKey, entry, finalTarget })\n }\n\n for (const [key, record] of [...registrations.entries()]) {\n if (!nextKeys.has(key)) {\n if (record.handle.isActive) {\n record.handle.unregister()\n }\n registrations.delete(key)\n }\n }\n\n for (const { registrationKey, entry, finalTarget } of prepared) {\n const existing = registrations.get(registrationKey)\n if (existing?.handle.isActive && existing.target === finalTarget) {\n existing.handle.callback = entry.callback\n const {\n target: _target,\n enabled: _enabled,\n ...restOptions\n } = entry.mergedOptions\n const optionsWithoutTarget = {\n ...restOptions,\n ...(entry.resolvedEnabled === undefined\n ? {}\n : { enabled: entry.resolvedEnabled }),\n }\n existing.handle.setOptions(optionsWithoutTarget)\n continue\n }\n\n if (existing) {\n if (existing.handle.isActive) {\n existing.handle.unregister()\n }\n registrations.delete(registrationKey)\n }\n\n const {\n target: _target,\n enabled: _enabled,\n ...restOptions\n } = entry.mergedOptions\n const optionsWithoutTarget = {\n ...restOptions,\n ...(entry.resolvedEnabled === undefined\n ? {}\n : { enabled: entry.resolvedEnabled }),\n }\n\n const handle = manager.register(entry.hotkeyString, entry.callback, {\n ...optionsWithoutTarget,\n target: finalTarget,\n })\n registrations.set(registrationKey, { handle, target: finalTarget })\n }\n },\n { immediate: true },\n )\n\n onUnmounted(() => {\n stopWatcher()\n for (const { handle } of registrations.values()) {\n if (handle.isActive) {\n handle.unregister()\n }\n }\n registrations.clear()\n })\n}\n\nfunction resolveMaybeRefOrGetter<T>(value: MaybeRefOrGetter<T>): T {\n return typeof value === 'function' ? (value as () => T)() : unref(value)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,SAAgB,WACd,SACA,gBAAoD,EAAE,EAChD;CAMN,MAAM,iBAAiB,0BAA0B;CACjD,MAAM,UAAU,kBAAkB;CAElC,MAAM,gCAAgB,IAAI,KAAiC;CAE3D,MAAM,cAAc,YACZ;EACJ,MAAM,kBAAkB,wBAAwB,QAAQ;EACxD,MAAM,wBAAwB,wBAAwB,cAAc;AAEpE,SAAO,gBAAgB,KAAK,KAAK,MAAM;GACrC,MAAM,iBAAiB,wBAAwB,IAAI,OAAO;GAC1D,MAAM,qBAAqB,IAAI,UAC3B,wBAAwB,IAAI,QAAQ,GACpC,EAAE;GAEN,MAAM,gBAAgB;IACpB,GAAG,eAAe;IAClB,GAAG;IACH,GAAG;IACJ;GAED,MAAM,WAAW,cAAc,YAAY,gBAAgB;GAC3D,MAAM,eACJ,OAAO,mBAAmB,WACtB,iBACC,aACC,wBAAwB,gBAAuB,SAAS,CACzD;GAEP,MAAM,kBACJ,cAAc,YAAY,SACtB,SACA,wBAAwB,cAAc,QAAQ;GACpD,MAAM,iBACJ,cAAc,WAAW,SACrB,SACA,wBAAwB,cAAc,OAAc;AAE1D,UAAO;IACL,OAAO;IACP;IACA,UAAU,IAAI;IACd;IACA;IACA;IACD;IACD;KAEH,aAAa;EACZ,MAAM,2BAAW,IAAI,KAAa;EAClC,MAAM,WAID,EAAE;AAEP,OAAK,MAAM,SAAS,UAAU;GAC5B,MAAM,cACJ,MAAM,mBACL,OAAO,aAAa,cAAc,WAAW;AAEhD,OAAI,CAAC,YACH;GAGF,MAAM,kBAAkB,GAAG,MAAM,MAAM,GAAG,MAAM;AAChD,YAAS,IAAI,gBAAgB;AAC7B,YAAS,KAAK;IAAE;IAAiB;IAAO;IAAa,CAAC;;AAGxD,OAAK,MAAM,CAAC,KAAK,WAAW,CAAC,GAAG,cAAc,SAAS,CAAC,CACtD,KAAI,CAAC,SAAS,IAAI,IAAI,EAAE;AACtB,OAAI,OAAO,OAAO,SAChB,QAAO,OAAO,YAAY;AAE5B,iBAAc,OAAO,IAAI;;AAI7B,OAAK,MAAM,EAAE,iBAAiB,OAAO,iBAAiB,UAAU;GAC9D,MAAM,WAAW,cAAc,IAAI,gBAAgB;AACnD,OAAI,UAAU,OAAO,YAAY,SAAS,WAAW,aAAa;AAChE,aAAS,OAAO,WAAW,MAAM;IACjC,MAAM,EACJ,QAAQ,SACR,SAAS,UACT,GAAG,gBACD,MAAM;IACV,MAAM,uBAAuB;KAC3B,GAAG;KACH,GAAI,MAAM,oBAAoB,SAC1B,EAAE,GACF,EAAE,SAAS,MAAM,iBAAiB;KACvC;AACD,aAAS,OAAO,WAAW,qBAAqB;AAChD;;AAGF,OAAI,UAAU;AACZ,QAAI,SAAS,OAAO,SAClB,UAAS,OAAO,YAAY;AAE9B,kBAAc,OAAO,gBAAgB;;GAGvC,MAAM,EACJ,QAAQ,SACR,SAAS,UACT,GAAG,gBACD,MAAM;GACV,MAAM,uBAAuB;IAC3B,GAAG;IACH,GAAI,MAAM,oBAAoB,SAC1B,EAAE,GACF,EAAE,SAAS,MAAM,iBAAiB;IACvC;GAED,MAAM,SAAS,QAAQ,SAAS,MAAM,cAAc,MAAM,UAAU;IAClE,GAAG;IACH,QAAQ;IACT,CAAC;AACF,iBAAc,IAAI,iBAAiB;IAAE;IAAQ,QAAQ;IAAa,CAAC;;IAGvE,EAAE,WAAW,MAAM,CACpB;AAED,mBAAkB;AAChB,eAAa;AACb,OAAK,MAAM,EAAE,YAAY,cAAc,QAAQ,CAC7C,KAAI,OAAO,SACT,QAAO,YAAY;AAGvB,gBAAc,OAAO;GACrB;;AAGJ,SAAS,wBAA2B,OAA+B;AACjE,QAAO,OAAO,UAAU,aAAc,OAAmB,GAAG,MAAM,MAAM"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/vue-hotkeys",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "description": "Vue adapter for TanStack Hotkeys",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -46,9 +46,9 @@
46
46
  "@tanstack/hotkeys": "0.4.2"
47
47
  },
48
48
  "devDependencies": {
49
- "@vitejs/plugin-vue": "^6.0.4",
49
+ "@vitejs/plugin-vue": "^6.0.5",
50
50
  "@vue/test-utils": "^2.4.6",
51
- "vue": "^3.5.29"
51
+ "vue": "^3.5.30"
52
52
  },
53
53
  "peerDependencies": {
54
54
  "vue": ">=3.0.0"
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ export * from './HotkeysProviderContext'
7
7
 
8
8
  // Vue-specific composables
9
9
  export * from './useHotkey'
10
+ export * from './useHotkeys'
10
11
  export * from './useHeldKeys'
11
12
  export * from './useHeldKeyCodes'
12
13
  export * from './useKeyHold'
@@ -0,0 +1,225 @@
1
+ import { onUnmounted, unref, watch } from 'vue'
2
+ import {
3
+ detectPlatform,
4
+ formatHotkey,
5
+ getHotkeyManager,
6
+ rawHotkeyToParsedHotkey,
7
+ } from '@tanstack/hotkeys'
8
+ import { useDefaultHotkeysOptions } from './HotkeysProviderContext'
9
+ import type { UseHotkeyOptions } from './useHotkey'
10
+ import type {
11
+ Hotkey,
12
+ HotkeyCallback,
13
+ HotkeyRegistrationHandle,
14
+ RegisterableHotkey,
15
+ } from '@tanstack/hotkeys'
16
+ import type { MaybeRefOrGetter } from 'vue'
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: MaybeRefOrGetter<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?: MaybeRefOrGetter<UseHotkeyOptions>
28
+ }
29
+
30
+ /**
31
+ * Vue composable 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.
36
+ *
37
+ * Options are merged in this order:
38
+ * HotkeysProvider defaults < commonOptions < per-definition options
39
+ *
40
+ * @param hotkeys - Array of hotkey definitions to register, or a getter/ref
41
+ * @param commonOptions - Shared options applied to all hotkeys (overridden by per-definition options)
42
+ *
43
+ * @example
44
+ * ```vue
45
+ * <script setup>
46
+ * import { useHotkeys } from '@tanstack/vue-hotkeys'
47
+ *
48
+ * useHotkeys([
49
+ * { hotkey: 'Mod+S', callback: () => save() },
50
+ * { hotkey: 'Mod+Z', callback: () => undo() },
51
+ * { hotkey: 'Escape', callback: () => close() },
52
+ * ])
53
+ * </script>
54
+ * ```
55
+ *
56
+ * @example
57
+ * ```vue
58
+ * <script setup>
59
+ * import { computed } from 'vue'
60
+ * import { useHotkeys } from '@tanstack/vue-hotkeys'
61
+ *
62
+ * const items = computed(() => [...])
63
+ * // Dynamic hotkeys from reactive data
64
+ * useHotkeys(
65
+ * () => items.value.map((item) => ({
66
+ * hotkey: item.shortcut,
67
+ * callback: item.action,
68
+ * options: { enabled: item.enabled },
69
+ * })),
70
+ * { preventDefault: true },
71
+ * )
72
+ * </script>
73
+ * ```
74
+ */
75
+ export function useHotkeys(
76
+ hotkeys: MaybeRefOrGetter<Array<UseHotkeyDefinition>>,
77
+ commonOptions: MaybeRefOrGetter<UseHotkeyOptions> = {},
78
+ ): void {
79
+ type RegistrationRecord = {
80
+ handle: HotkeyRegistrationHandle
81
+ target: Document | HTMLElement | Window
82
+ }
83
+
84
+ const defaultOptions = useDefaultHotkeysOptions()
85
+ const manager = getHotkeyManager()
86
+
87
+ const registrations = new Map<string, RegistrationRecord>()
88
+
89
+ const stopWatcher = watch(
90
+ () => {
91
+ const resolvedHotkeys = resolveMaybeRefOrGetter(hotkeys)
92
+ const resolvedCommonOptions = resolveMaybeRefOrGetter(commonOptions)
93
+
94
+ return resolvedHotkeys.map((def, i) => {
95
+ const resolvedHotkey = resolveMaybeRefOrGetter(def.hotkey)
96
+ const resolvedDefOptions = def.options
97
+ ? resolveMaybeRefOrGetter(def.options)
98
+ : {}
99
+
100
+ const mergedOptions = {
101
+ ...defaultOptions.hotkey,
102
+ ...resolvedCommonOptions,
103
+ ...resolvedDefOptions,
104
+ } as UseHotkeyOptions
105
+
106
+ const platform = mergedOptions.platform ?? detectPlatform()
107
+ const hotkeyString: Hotkey =
108
+ typeof resolvedHotkey === 'string'
109
+ ? resolvedHotkey
110
+ : (formatHotkey(
111
+ rawHotkeyToParsedHotkey(resolvedHotkey as any, platform),
112
+ ) as Hotkey)
113
+
114
+ const resolvedEnabled =
115
+ mergedOptions.enabled === undefined
116
+ ? undefined
117
+ : resolveMaybeRefOrGetter(mergedOptions.enabled)
118
+ const resolvedTarget =
119
+ mergedOptions.target === undefined
120
+ ? undefined
121
+ : resolveMaybeRefOrGetter(mergedOptions.target as any)
122
+
123
+ return {
124
+ index: i,
125
+ hotkeyString,
126
+ callback: def.callback,
127
+ mergedOptions,
128
+ resolvedEnabled,
129
+ resolvedTarget,
130
+ }
131
+ })
132
+ },
133
+ (resolved) => {
134
+ const nextKeys = new Set<string>()
135
+ const prepared: Array<{
136
+ registrationKey: string
137
+ entry: (typeof resolved)[number]
138
+ finalTarget: Document | HTMLElement | Window
139
+ }> = []
140
+
141
+ for (const entry of resolved) {
142
+ const finalTarget =
143
+ entry.resolvedTarget ??
144
+ (typeof document !== 'undefined' ? document : null)
145
+
146
+ if (!finalTarget) {
147
+ continue
148
+ }
149
+
150
+ const registrationKey = `${entry.index}:${entry.hotkeyString}`
151
+ nextKeys.add(registrationKey)
152
+ prepared.push({ registrationKey, entry, finalTarget })
153
+ }
154
+
155
+ for (const [key, record] of [...registrations.entries()]) {
156
+ if (!nextKeys.has(key)) {
157
+ if (record.handle.isActive) {
158
+ record.handle.unregister()
159
+ }
160
+ registrations.delete(key)
161
+ }
162
+ }
163
+
164
+ for (const { registrationKey, entry, finalTarget } of prepared) {
165
+ const existing = registrations.get(registrationKey)
166
+ if (existing?.handle.isActive && existing.target === finalTarget) {
167
+ existing.handle.callback = entry.callback
168
+ const {
169
+ target: _target,
170
+ enabled: _enabled,
171
+ ...restOptions
172
+ } = entry.mergedOptions
173
+ const optionsWithoutTarget = {
174
+ ...restOptions,
175
+ ...(entry.resolvedEnabled === undefined
176
+ ? {}
177
+ : { enabled: entry.resolvedEnabled }),
178
+ }
179
+ existing.handle.setOptions(optionsWithoutTarget)
180
+ continue
181
+ }
182
+
183
+ if (existing) {
184
+ if (existing.handle.isActive) {
185
+ existing.handle.unregister()
186
+ }
187
+ registrations.delete(registrationKey)
188
+ }
189
+
190
+ const {
191
+ target: _target,
192
+ enabled: _enabled,
193
+ ...restOptions
194
+ } = entry.mergedOptions
195
+ const optionsWithoutTarget = {
196
+ ...restOptions,
197
+ ...(entry.resolvedEnabled === undefined
198
+ ? {}
199
+ : { enabled: entry.resolvedEnabled }),
200
+ }
201
+
202
+ const handle = manager.register(entry.hotkeyString, entry.callback, {
203
+ ...optionsWithoutTarget,
204
+ target: finalTarget,
205
+ })
206
+ registrations.set(registrationKey, { handle, target: finalTarget })
207
+ }
208
+ },
209
+ { immediate: true },
210
+ )
211
+
212
+ onUnmounted(() => {
213
+ stopWatcher()
214
+ for (const { handle } of registrations.values()) {
215
+ if (handle.isActive) {
216
+ handle.unregister()
217
+ }
218
+ }
219
+ registrations.clear()
220
+ })
221
+ }
222
+
223
+ function resolveMaybeRefOrGetter<T>(value: MaybeRefOrGetter<T>): T {
224
+ return typeof value === 'function' ? (value as () => T)() : unref(value)
225
+ }