hotkey-router 0.3.2 → 0.4.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.
@@ -1,582 +1,14 @@
1
- // hotkey-router v0.3.2 | SEE LICENSE IN LICENSE
1
+ // hotkey-router v0.4.0 | SEE LICENSE IN LICENSE
2
2
 
3
3
 
4
- // platform.js
5
- function fromPlatformString(s) {
6
- if (!s) return null;
7
- if (/Chrome ?OS|CrOS/i.test(s)) return "chromeos";
8
- if (/Mac|iPhone|iPad|iPod/i.test(s)) return "mac";
9
- if (/Win/i.test(s)) return "windows";
10
- if (/Linux|X11/i.test(s)) return "linux";
11
- return null;
12
- }
13
- function detectPlatform(nav = typeof navigator !== "undefined" ? navigator : null, { chromeos = false } = {}) {
14
- if (!nav) return null;
15
- const ua = nav.userAgent || "";
16
- const found = (/\bCrOS\b/.test(ua) ? "chromeos" : null) || fromPlatformString(nav.userAgentData?.platform) || fromPlatformString(nav.platform) || (/Mac OS X/i.test(ua) ? "mac" : /Windows/i.test(ua) ? "windows" : /Linux|X11/i.test(ua) ? "linux" : null);
17
- if (found === "chromeos" && !chromeos) return "linux";
18
- return found;
19
- }
20
-
21
- // parse.js
22
- var DEFAULT_PLATFORM = detectPlatform();
23
- var modifierTokens = /* @__PURE__ */ new Set(["ctrl", "shift", "alt", "meta", "mod"]);
24
- var ahkPrefixMap = /* @__PURE__ */ new Map([
25
- ["^", "ctrl"],
26
- // Ctrl
27
- ["!", "alt"],
28
- // Alt
29
- ["+", "shift"],
30
- // Shift
31
- ["#", "meta"]
32
- // Win / Command
33
- ]);
34
- var keyAliases = Object.freeze({
35
- // common
36
- esc: "escape",
37
- escape: "escape",
38
- space: " ",
39
- spacebar: " ",
40
- enter: "enter",
41
- return: "enter",
42
- del: "delete",
43
- delete: "delete",
44
- backspace: "backspace",
45
- tab: "tab",
46
- // arrows
47
- up: "arrowup",
48
- down: "arrowdown",
49
- left: "arrowleft",
50
- right: "arrowright",
51
- // navigation
52
- home: "home",
53
- end: "end",
54
- pageup: "pageup",
55
- pagedown: "pagedown",
56
- pgup: "pageup",
57
- pgdn: "pagedown",
58
- // modifiers (words)
59
- cmd: "meta",
60
- command: "meta",
61
- win: "meta",
62
- meta: "meta",
63
- control: "ctrl",
64
- ctrl: "ctrl",
65
- option: "alt",
66
- opt: "alt",
67
- alt: "alt",
68
- shift: "shift",
69
- // modifiers (symbols)
70
- "\u2318": "meta",
71
- "\u2303": "ctrl",
72
- "\u2325": "alt",
73
- "\u21E7": "shift",
74
- // cross-platform "mod", resolved per platform while parsing
75
- mod: "mod",
76
- // plus key ergonomics
77
- plus: "+"
78
- });
79
- function normalizeKey(key) {
80
- const original = String(key ?? "");
81
- if (original === " ") return " ";
82
- const trimmed = original.trim();
83
- const k = trimmed.toLowerCase();
84
- return keyAliases[k] ?? k;
85
- }
86
- function isModifierToken(token) {
87
- return modifierTokens.has(normalizeKey(token));
88
- }
89
- var CODE_TOKEN_RE = /(^|\+)code:([A-Za-z][A-Za-z0-9_]*)/;
90
- function readHotkey(hotkeyStr, { platform = DEFAULT_PLATFORM } = {}) {
91
- const raw = String(hotkeyStr || "").trim();
92
- let error = null;
93
- const fail = (msg) => {
94
- error = error || `Invalid hotkey "${hotkeyStr}": ${msg}`;
95
- };
96
- const isUp = /\s+up$/i.test(raw);
97
- const baseRaw = isUp ? raw.replace(/\s+up$/i, "").trim() : raw;
98
- const combo = {
99
- ctrl: false,
100
- shift: false,
101
- alt: false,
102
- meta: false,
103
- key: null,
104
- code: null,
105
- bareModifier: null
106
- };
107
- const setMod = (mod) => {
108
- if (mod === "mod") combo[platform === "mac" ? "meta" : "ctrl"] = true;
109
- else combo[mod] = true;
110
- };
111
- let stripped = baseRaw;
112
- while (stripped.length) {
113
- const mod = ahkPrefixMap.get(stripped[0]) ?? null;
114
- if (!mod) break;
115
- setMod(mod);
116
- stripped = stripped.slice(1).trimStart();
117
- }
118
- const codeMatches = stripped.match(/code:[A-Za-z][A-Za-z0-9_]*/g);
119
- if (codeMatches && codeMatches.length > 1) {
120
- fail(`multiple code: tokens not supported (got ${codeMatches.length}).`);
121
- }
122
- let codeValue = null;
123
- const scrubbed = stripped.replace(CODE_TOKEN_RE, (_, sep, val) => {
124
- codeValue = val;
125
- return sep + "__code__";
126
- });
127
- const cleanStr = scrubbed.toLowerCase();
128
- const rawParts = cleanStr.split("+").map((p) => p.trim());
129
- const parts = rawParts.filter(Boolean);
130
- const impliedPlusKey = rawParts.some((p) => p === "") && cleanStr.includes("++");
131
- if (!impliedPlusKey) {
132
- let seenBase = false;
133
- for (const part of parts) {
134
- if (isModifierToken(part)) {
135
- if (seenBase) fail('modifiers must come before the base key (e.g. "ctrl+k", not "k+ctrl")');
136
- } else {
137
- seenBase = true;
138
- }
139
- }
140
- }
141
- for (const part of parts) {
142
- if (part === "__code__") {
143
- combo.code = codeValue;
144
- continue;
145
- }
146
- const actual = keyAliases[part] ?? part;
147
- if (modifierTokens.has(actual)) setMod(actual);
148
- else combo.key = normalizeKey(actual);
149
- }
150
- if (!combo.key && !combo.code && impliedPlusKey) combo.key = "+";
151
- if (!combo.key && !combo.code) {
152
- const modCount = (combo.ctrl ? 1 : 0) + (combo.shift ? 1 : 0) + (combo.alt ? 1 : 0) + (combo.meta ? 1 : 0);
153
- if (modCount === 1) {
154
- combo.bareModifier = combo.ctrl ? "ctrl" : combo.shift ? "shift" : combo.alt ? "alt" : "meta";
155
- } else if (modCount > 1) {
156
- fail('multi-modifier bare bindings not supported. Add a base key (e.g. "ctrl+alt+x").');
157
- } else {
158
- error = error || `Invalid hotkey "${hotkeyStr}" (missing base key)`;
159
- }
160
- }
161
- return { combo, type: isUp ? "keyup" : "keydown", raw: hotkeyStr, error };
162
- }
163
- function parseHotkey(hotkeyStr, opts) {
164
- const { combo, type, raw, error } = readHotkey(hotkeyStr, opts);
165
- if (error) throw new Error(error);
166
- return { combo, type, raw };
167
- }
168
-
169
4
  // hotkey-router.js
170
- function on(target, type, fn, options) {
171
- target.addEventListener(type, fn, options);
172
- return () => target.removeEventListener(type, fn, options);
173
- }
174
- var PLATFORM = detectPlatform();
175
- var MODIFIER_KEY_TOKEN = Object.freeze({
176
- Alt: "alt",
177
- AltGraph: "alt",
178
- Control: "ctrl",
179
- Shift: "shift",
180
- Meta: "meta",
181
- OS: "meta"
182
- });
183
- var ignoreEditable = true;
184
- var defaultTarget = typeof window !== "undefined" ? window : null;
185
- var bindHooks = [];
186
- var registry = /* @__PURE__ */ new Map();
187
- var plugins = /* @__PURE__ */ new Map();
188
- var bindingIndex = /* @__PURE__ */ new Map();
189
- var paused = false;
190
- var nextId = 1;
191
- function comboKeyFromParts({ ctrl, shift, alt, meta, key, code, bareModifier }) {
192
- if (bareModifier) return `__bare__:${bareModifier}`;
193
- let s = "";
194
- if (ctrl) s += "ctrl+";
195
- if (shift) s += "shift+";
196
- if (alt) s += "alt+";
197
- if (meta) s += "meta+";
198
- if (code) return s + "code:" + code;
199
- return s ? s + key : key;
200
- }
201
- function comboKeyFromEvent(e) {
202
- const bareMod = MODIFIER_KEY_TOKEN[e.key];
203
- if (bareMod) return `__bare__:${bareMod}`;
204
- return comboKeyFromParts({
205
- ctrl: e.ctrlKey,
206
- shift: e.shiftKey,
207
- alt: e.altKey,
208
- meta: e.metaKey,
209
- key: normalizeKey(e.key)
210
- });
211
- }
212
- function codeKeyFromEvent(e) {
213
- if (!e.code) return null;
214
- let s = "";
215
- if (e.ctrlKey) s += "ctrl+";
216
- if (e.shiftKey) s += "shift+";
217
- if (e.altKey) s += "alt+";
218
- if (e.metaKey) s += "meta+";
219
- return s + "code:" + e.code;
220
- }
221
- function isFromInputTarget(e) {
222
- const t = e?.target;
223
- if (!t) return false;
224
- const tag = String(t.tagName || "").toUpperCase();
225
- return t.isContentEditable || tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || t.getAttribute?.("role") === "textbox";
226
- }
227
- function normalizeOptions(type, options) {
228
- const o = options ? { ...options } : {};
229
- if (type === "keydown" && o.repeat == null) o.repeat = false;
230
- if (o.priority == null) o.priority = 0;
231
- return o;
232
- }
233
- function ensureSlot(comboStr, type) {
234
- let typeMap = registry.get(comboStr);
235
- if (!typeMap) {
236
- typeMap = /* @__PURE__ */ new Map();
237
- registry.set(comboStr, typeMap);
238
- }
239
- let arr = typeMap.get(type);
240
- if (!arr) {
241
- arr = [];
242
- typeMap.set(type, arr);
243
- }
244
- return arr;
245
- }
246
- function removeById(id) {
247
- const idx = bindingIndex.get(id);
248
- if (!idx) return false;
249
- const { comboStr, type } = idx;
250
- const typeMap = registry.get(comboStr);
251
- const arr = typeMap?.get(type);
252
- if (!arr?.length) {
253
- bindingIndex.delete(id);
254
- return false;
255
- }
256
- const next = arr.filter((b) => b.id !== id);
257
- if (next.length) typeMap.set(type, next);
258
- else typeMap.delete(type);
259
- if (!typeMap.size) registry.delete(comboStr);
260
- bindingIndex.delete(id);
261
- return true;
262
- }
263
- function bind(hotkeyStr, handler, plugin = null, options = {}) {
264
- const { combo, type, raw } = parseHotkey(hotkeyStr);
265
- const comboStr = comboKeyFromParts(combo);
266
- const opts = normalizeOptions(type, options);
267
- const binding = {
268
- id: nextId++,
269
- comboStr,
270
- type,
271
- combo,
272
- handler,
273
- plugin,
274
- raw,
275
- options: opts
276
- };
277
- ensureSlot(comboStr, type).push(binding);
278
- bindingIndex.set(binding.id, { comboStr, type });
279
- if (bindHooks.length) {
280
- for (const hook of bindHooks) {
281
- try {
282
- hook({ combo, raw, options: opts, plugin, id: binding.id });
283
- } catch (err) {
284
- console.error("[hotkey-router] onBind hook threw:", err);
285
- }
286
- }
287
- }
288
- const off = () => removeById(binding.id);
289
- off.id = binding.id;
290
- off.hotkey = raw;
291
- return off;
292
- }
293
- function onBind(hook) {
294
- if (typeof hook !== "function") {
295
- throw new TypeError("hotkeys.onBind(hook) expects a function");
296
- }
297
- bindHooks.push(hook);
298
- return () => {
299
- bindHooks = bindHooks.filter((h) => h !== hook);
300
- };
301
- }
302
- function unbind(hotkeyStr, handler) {
303
- const { combo, type } = parseHotkey(hotkeyStr);
304
- const comboStr = comboKeyFromParts(combo);
305
- const typeMap = registry.get(comboStr);
306
- if (!typeMap) return;
307
- const arr = typeMap.get(type);
308
- if (!arr?.length) return;
309
- if (!handler) {
310
- for (const b of arr) bindingIndex.delete(b.id);
311
- typeMap.delete(type);
312
- } else {
313
- const keep = [];
314
- for (const b of arr) {
315
- if (b.handler === handler) bindingIndex.delete(b.id);
316
- else keep.push(b);
317
- }
318
- if (keep.length) typeMap.set(type, keep);
319
- else typeMap.delete(type);
320
- }
321
- if (!typeMap.size) registry.delete(comboStr);
322
- }
323
- function registerPlugin(name, hotkeyMap) {
324
- if (plugins.has(name)) throw new Error(`Plugin "${name}" already registered`);
325
- const ids = [];
326
- for (const [hotkeyStr, fnOrTuple] of Object.entries(hotkeyMap)) {
327
- const [fn, options] = Array.isArray(fnOrTuple) ? fnOrTuple : [fnOrTuple, {}];
328
- const off = bind(hotkeyStr, fn, name, options);
329
- ids.push(off.id);
330
- }
331
- plugins.set(name, ids);
332
- return () => unregisterPlugin(name);
333
- }
334
- function unregisterPlugin(name) {
335
- const ids = plugins.get(name);
336
- if (!ids) return;
337
- for (const id of ids) removeById(id);
338
- plugins.delete(name);
339
- }
340
- function pause() {
341
- paused = true;
342
- }
343
- function resume() {
344
- paused = false;
345
- }
346
- function ignoreInput(value = true) {
347
- ignoreEditable = !!value;
348
- }
349
- function setTarget(target) {
350
- defaultTarget = target;
351
- }
352
- function pickWinner(bindings) {
353
- let best = null;
354
- for (const b of bindings) {
355
- if (!best) best = b;
356
- else if (b.options.priority > best.options.priority) best = b;
357
- else if (b.options.priority === best.options.priority && b.id > best.id) best = b;
358
- }
359
- return best;
360
- }
361
- function isAltGraphCharacter(e) {
362
- return Boolean(
363
- e.ctrlKey && e.altKey && typeof e.getModifierState === "function" && e.getModifierState("AltGraph") && typeof e.key === "string" && e.key.length === 1
364
- );
365
- }
366
- function isComposingEvent(e) {
367
- return Boolean(e.isComposing || e.keyCode === 229);
368
- }
369
- function eligibleBindings(e, type, phase) {
370
- const altGraphChar = isAltGraphCharacter(e);
371
- const composing = isComposingEvent(e);
372
- const fromInput = ignoreEditable && isFromInputTarget(e);
373
- const seen = /* @__PURE__ */ new Set();
374
- const candidates = [];
375
- for (const lookupKey of [comboKeyFromEvent(e), codeKeyFromEvent(e)]) {
376
- if (!lookupKey || seen.has(lookupKey)) continue;
377
- seen.add(lookupKey);
378
- const bindings = registry.get(lookupKey)?.get(type);
379
- if (!bindings?.length) continue;
380
- for (const b of bindings) {
381
- const o = b.options;
382
- if (phase === "capture" && !o.capture) continue;
383
- if (phase === "bubble" && o.capture) continue;
384
- if (altGraphChar && !o.altGraph) continue;
385
- if (composing && !o.composing) continue;
386
- if (fromInput && !o.allowIn?.(e)) continue;
387
- if (type === "keydown" && o.repeat === false && e.repeat) continue;
388
- if (o.when && o.when(e) === false) continue;
389
- candidates.push(b);
390
- }
391
- }
392
- return candidates;
393
- }
394
- function fire(winner, e) {
395
- const o = winner.options;
396
- if (o.preventDefault) e.preventDefault();
397
- if (o.stopImmediatePropagation) e.stopImmediatePropagation();
398
- else if (o.stopPropagation) e.stopPropagation();
399
- winner.handler(e);
400
- if (o.once) removeById(winner.id);
401
- }
402
- function handleEvent(type, phase = "all") {
403
- return (e) => {
404
- if (paused) return;
405
- const candidates = eligibleBindings(e, type, phase);
406
- if (candidates.length) fire(pickWinner(candidates), e);
407
- };
408
- }
409
- var stopDown = null;
410
- var stopUp = null;
411
- var stopCaptureDown = null;
412
- var stopCaptureUp = null;
413
- function init({ target = defaultTarget, capture = false } = {}) {
414
- if (!target) throw new Error("hotkeys.init() requires a target (e.g. window)");
415
- if (stopDown || stopUp) destroy();
416
- if (capture) {
417
- stopDown = on(target, "keydown", handleEvent("keydown"), { capture: true });
418
- stopUp = on(target, "keyup", handleEvent("keyup"), { capture: true });
419
- return;
420
- }
421
- stopDown = on(target, "keydown", handleEvent("keydown", "bubble"), { capture: false });
422
- stopUp = on(target, "keyup", handleEvent("keyup", "bubble"), { capture: false });
423
- stopCaptureDown = on(target, "keydown", handleEvent("keydown", "capture"), { capture: true });
424
- stopCaptureUp = on(target, "keyup", handleEvent("keyup", "capture"), { capture: true });
425
- }
426
- function destroy() {
427
- stopDown?.();
428
- stopUp?.();
429
- stopCaptureDown?.();
430
- stopCaptureUp?.();
431
- stopDown = null;
432
- stopUp = null;
433
- stopCaptureDown = null;
434
- stopCaptureUp = null;
435
- registry.clear();
436
- plugins.clear();
437
- bindingIndex.clear();
438
- }
439
- var BARE_MOD_TO_KEY = {
440
- ctrl: "Control",
441
- shift: "Shift",
442
- alt: "Alt",
443
- meta: "Meta"
444
- };
445
- var CODE_TO_KEY = {
446
- Period: ".",
447
- Comma: ",",
448
- Semicolon: ";",
449
- Quote: "'",
450
- Slash: "/",
451
- Backslash: "\\",
452
- BracketLeft: "[",
453
- BracketRight: "]",
454
- Minus: "-",
455
- Equal: "=",
456
- Backquote: "`",
457
- Space: " ",
458
- Enter: "Enter",
459
- NumpadEnter: "Enter",
460
- Tab: "Tab",
461
- Escape: "Escape",
462
- Backspace: "Backspace",
463
- Delete: "Delete",
464
- Insert: "Insert",
465
- Home: "Home",
466
- End: "End",
467
- PageUp: "PageUp",
468
- PageDown: "PageDown",
469
- ArrowUp: "ArrowUp",
470
- ArrowDown: "ArrowDown",
471
- ArrowLeft: "ArrowLeft",
472
- ArrowRight: "ArrowRight"
473
- };
474
- var KEY_TO_CODE = {};
475
- var _a;
476
- for (const [code, key] of Object.entries(CODE_TO_KEY)) {
477
- KEY_TO_CODE[_a = normalizeKey(key)] ?? (KEY_TO_CODE[_a] = code);
478
- }
479
- function keyForCode(code) {
480
- if (!code) return null;
481
- const letter = /^Key([A-Z])$/.exec(code);
482
- if (letter) return letter[1].toLowerCase();
483
- const digit = /^(?:Digit|Numpad)(\d)$/.exec(code);
484
- if (digit) return digit[1];
485
- if (/^F\d{1,2}$/.test(code)) return code;
486
- return CODE_TO_KEY[code] ?? null;
487
- }
488
- function codeForKey(key) {
489
- if (!key) return null;
490
- if (/^[a-z]$/.test(key)) return "Key" + key.toUpperCase();
491
- if (/^\d$/.test(key)) return "Digit" + key;
492
- if (/^f\d{1,2}$/.test(key)) return key.toUpperCase();
493
- return KEY_TO_CODE[key] ?? null;
494
- }
495
- function trigger(hotkeyStr, { type: forcedType, target = null } = {}) {
496
- const { combo, type } = parseHotkey(hotkeyStr);
497
- const actualType = forcedType || type;
498
- if (paused) return false;
499
- const eventKey = combo.bareModifier ? BARE_MOD_TO_KEY[combo.bareModifier] : combo.key ?? keyForCode(combo.code);
500
- const eventCode = combo.bareModifier ? null : combo.code ?? codeForKey(combo.key);
501
- let altKey = !!combo.alt;
502
- let ctrlKey = !!combo.ctrl;
503
- let shiftKey = !!combo.shift;
504
- let metaKey = !!combo.meta;
505
- if (combo.bareModifier && actualType === "keyup") {
506
- if (combo.bareModifier === "alt") altKey = false;
507
- else if (combo.bareModifier === "ctrl") ctrlKey = false;
508
- else if (combo.bareModifier === "shift") shiftKey = false;
509
- else if (combo.bareModifier === "meta") metaKey = false;
510
- }
511
- const e = {
512
- type: actualType,
513
- key: eventKey,
514
- code: eventCode,
515
- ctrlKey,
516
- shiftKey,
517
- altKey,
518
- metaKey,
519
- repeat: false,
520
- isComposing: false,
521
- getModifierState() {
522
- return false;
523
- },
524
- preventDefault() {
525
- },
526
- stopPropagation() {
527
- },
528
- stopImmediatePropagation() {
529
- },
530
- target
531
- };
532
- const candidates = eligibleBindings(e, actualType, "all");
533
- if (!candidates.length) return false;
534
- fire(pickWinner(candidates), e);
535
- return true;
536
- }
537
- function comboFromEvent(e, { physical = true, useMod = false, platform = PLATFORM } = {}) {
538
- if (!e || MODIFIER_KEY_TOKEN[e.key]) return null;
539
- const parts = [];
540
- const primaryIsMeta = platform === "mac";
541
- if (useMod && (primaryIsMeta ? e.metaKey : e.ctrlKey)) parts.push("mod");
542
- if (e.ctrlKey && !(useMod && !primaryIsMeta)) parts.push("ctrl");
543
- if (e.metaKey && !(useMod && primaryIsMeta)) parts.push("meta");
544
- if (e.altKey) parts.push("alt");
545
- if (e.shiftKey) parts.push("shift");
546
- if (physical && e.code) parts.push(`code:${e.code}`);
547
- else {
548
- const key = normalizeKey(e.key);
549
- if (!key) return null;
550
- parts.push(key === " " ? "space" : key);
551
- }
552
- return parts.join("+");
553
- }
554
- if (defaultTarget) init();
555
- var hotkey_router_default = {
556
- // lifecycle
557
- init,
558
- destroy,
559
- setTarget,
560
- // bindings
561
- bind,
562
- unbind,
563
- registerPlugin,
564
- unregisterPlugin,
565
- // extension hooks
566
- onBind,
567
- // control
568
- pause,
569
- resume,
570
- ignoreInput,
571
- // testing / automation
572
- trigger,
573
- // helpers
574
- parseHotkey,
575
- comboFromEvent,
576
- detectPlatform
577
- };
5
+ import { createRouter, parseHotkey, comboFromEvent, detectPlatform } from "./core.js";
6
+ var hotkeys = createRouter();
7
+ if (typeof window !== "undefined") hotkeys.init();
8
+ var hotkey_router_default = hotkeys;
578
9
  export {
579
10
  comboFromEvent,
11
+ createRouter,
580
12
  hotkey_router_default as default,
581
13
  detectPlatform,
582
14
  parseHotkey