hotkey-router 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,21 +1,26 @@
1
- // hotkey-router v0.3.0 | SEE LICENSE IN LICENSE
1
+ // hotkey-router v0.3.2 | SEE LICENSE IN LICENSE
2
2
 
3
3
 
4
- // hotkey-router.js
5
- function on(target, type, fn, options) {
6
- target.addEventListener(type, fn, options);
7
- return () => target.removeEventListener(type, fn, options);
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;
8
12
  }
9
- var isMac = typeof navigator !== "undefined" && /Mac|iPhone|iPad|iPod/.test(navigator.platform);
10
- var modifierTokens = /* @__PURE__ */ new Set(["ctrl", "shift", "alt", "meta"]);
11
- var MODIFIER_KEY_TOKEN = Object.freeze({
12
- Alt: "alt",
13
- AltGraph: "alt",
14
- Control: "ctrl",
15
- Shift: "shift",
16
- Meta: "meta",
17
- OS: "meta"
18
- });
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"]);
19
24
  var ahkPrefixMap = /* @__PURE__ */ new Map([
20
25
  ["^", "ctrl"],
21
26
  // Ctrl
@@ -58,6 +63,7 @@ var keyAliases = Object.freeze({
58
63
  control: "ctrl",
59
64
  ctrl: "ctrl",
60
65
  option: "alt",
66
+ opt: "alt",
61
67
  alt: "alt",
62
68
  shift: "shift",
63
69
  // modifiers (symbols)
@@ -65,19 +71,11 @@ var keyAliases = Object.freeze({
65
71
  "\u2303": "ctrl",
66
72
  "\u2325": "alt",
67
73
  "\u21E7": "shift",
68
- // cross-platform "mod"
69
- mod: isMac ? "meta" : "ctrl",
74
+ // cross-platform "mod", resolved per platform while parsing
75
+ mod: "mod",
70
76
  // plus key ergonomics
71
77
  plus: "+"
72
78
  });
73
- var ignoreEditable = true;
74
- var defaultTarget = typeof window !== "undefined" ? window : null;
75
- var bindHooks = [];
76
- var registry = /* @__PURE__ */ new Map();
77
- var plugins = /* @__PURE__ */ new Map();
78
- var bindingIndex = /* @__PURE__ */ new Map();
79
- var paused = false;
80
- var nextId = 1;
81
79
  function normalizeKey(key) {
82
80
  const original = String(key ?? "");
83
81
  if (original === " ") return " ";
@@ -85,43 +83,16 @@ function normalizeKey(key) {
85
83
  const k = trimmed.toLowerCase();
86
84
  return keyAliases[k] ?? k;
87
85
  }
88
- function comboKeyFromParts({ ctrl, shift, alt, meta, key, code, bareModifier }) {
89
- if (bareModifier) return `__bare__:${bareModifier}`;
90
- let s = "";
91
- if (ctrl) s += "ctrl+";
92
- if (shift) s += "shift+";
93
- if (alt) s += "alt+";
94
- if (meta) s += "meta+";
95
- if (code) return s + "code:" + code;
96
- return s ? s + key : key;
97
- }
98
- function comboKeyFromEvent(e) {
99
- const bareMod = MODIFIER_KEY_TOKEN[e.key];
100
- if (bareMod) return `__bare__:${bareMod}`;
101
- return comboKeyFromParts({
102
- ctrl: e.ctrlKey,
103
- shift: e.shiftKey,
104
- alt: e.altKey,
105
- meta: e.metaKey,
106
- key: normalizeKey(e.key)
107
- });
108
- }
109
- function codeKeyFromEvent(e) {
110
- if (!e.code) return null;
111
- let s = "";
112
- if (e.ctrlKey) s += "ctrl+";
113
- if (e.shiftKey) s += "shift+";
114
- if (e.altKey) s += "alt+";
115
- if (e.metaKey) s += "meta+";
116
- return s + "code:" + e.code;
117
- }
118
86
  function isModifierToken(token) {
119
- const t = normalizeKey(token);
120
- return modifierTokens.has(t);
87
+ return modifierTokens.has(normalizeKey(token));
121
88
  }
122
89
  var CODE_TOKEN_RE = /(^|\+)code:([A-Za-z][A-Za-z0-9_]*)/;
123
- function parseHotkey(hotkeyStr) {
90
+ function readHotkey(hotkeyStr, { platform = DEFAULT_PLATFORM } = {}) {
124
91
  const raw = String(hotkeyStr || "").trim();
92
+ let error = null;
93
+ const fail = (msg) => {
94
+ error = error || `Invalid hotkey "${hotkeyStr}": ${msg}`;
95
+ };
125
96
  const isUp = /\s+up$/i.test(raw);
126
97
  const baseRaw = isUp ? raw.replace(/\s+up$/i, "").trim() : raw;
127
98
  const combo = {
@@ -133,25 +104,27 @@ function parseHotkey(hotkeyStr) {
133
104
  code: null,
134
105
  bareModifier: null
135
106
  };
107
+ const setMod = (mod) => {
108
+ if (mod === "mod") combo[platform === "mac" ? "meta" : "ctrl"] = true;
109
+ else combo[mod] = true;
110
+ };
136
111
  let stripped = baseRaw;
137
112
  while (stripped.length) {
138
113
  const mod = ahkPrefixMap.get(stripped[0]) ?? null;
139
114
  if (!mod) break;
140
- combo[mod] = true;
115
+ setMod(mod);
141
116
  stripped = stripped.slice(1).trimStart();
142
117
  }
143
118
  const codeMatches = stripped.match(/code:[A-Za-z][A-Za-z0-9_]*/g);
144
119
  if (codeMatches && codeMatches.length > 1) {
145
- throw new Error(
146
- `Invalid hotkey "${hotkeyStr}": multiple code: tokens not supported (got ${codeMatches.length}).`
147
- );
120
+ fail(`multiple code: tokens not supported (got ${codeMatches.length}).`);
148
121
  }
149
122
  let codeValue = null;
150
123
  const scrubbed = stripped.replace(CODE_TOKEN_RE, (_, sep, val) => {
151
124
  codeValue = val;
152
125
  return sep + "__code__";
153
126
  });
154
- let cleanStr = scrubbed.toLowerCase();
127
+ const cleanStr = scrubbed.toLowerCase();
155
128
  const rawParts = cleanStr.split("+").map((p) => p.trim());
156
129
  const parts = rawParts.filter(Boolean);
157
130
  const impliedPlusKey = rawParts.some((p) => p === "") && cleanStr.includes("++");
@@ -159,13 +132,9 @@ function parseHotkey(hotkeyStr) {
159
132
  let seenBase = false;
160
133
  for (const part of parts) {
161
134
  if (isModifierToken(part)) {
162
- if (seenBase) {
163
- throw new Error(
164
- `Invalid hotkey "${hotkeyStr}": modifiers must come before the base key (e.g. "ctrl+k", not "k+ctrl")`
165
- );
166
- }
135
+ if (seenBase) fail('modifiers must come before the base key (e.g. "ctrl+k", not "k+ctrl")');
167
136
  } else {
168
- if (!seenBase) seenBase = true;
137
+ seenBase = true;
169
138
  }
170
139
  }
171
140
  }
@@ -175,10 +144,7 @@ function parseHotkey(hotkeyStr) {
175
144
  continue;
176
145
  }
177
146
  const actual = keyAliases[part] ?? part;
178
- if (actual === "ctrl") combo.ctrl = true;
179
- else if (actual === "shift") combo.shift = true;
180
- else if (actual === "alt") combo.alt = true;
181
- else if (actual === "meta") combo.meta = true;
147
+ if (modifierTokens.has(actual)) setMod(actual);
182
148
  else combo.key = normalizeKey(actual);
183
149
  }
184
150
  if (!combo.key && !combo.code && impliedPlusKey) combo.key = "+";
@@ -187,14 +153,70 @@ function parseHotkey(hotkeyStr) {
187
153
  if (modCount === 1) {
188
154
  combo.bareModifier = combo.ctrl ? "ctrl" : combo.shift ? "shift" : combo.alt ? "alt" : "meta";
189
155
  } else if (modCount > 1) {
190
- throw new Error(
191
- `Invalid hotkey "${hotkeyStr}": multi-modifier bare bindings not supported. Add a base key (e.g. "ctrl+alt+x").`
192
- );
156
+ fail('multi-modifier bare bindings not supported. Add a base key (e.g. "ctrl+alt+x").');
193
157
  } else {
194
- throw new Error(`Invalid hotkey "${hotkeyStr}" (missing base key)`);
158
+ error = error || `Invalid hotkey "${hotkeyStr}" (missing base key)`;
195
159
  }
196
160
  }
197
- return { combo, type: isUp ? "keyup" : "keydown", raw: hotkeyStr };
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
+ // 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;
198
220
  }
199
221
  function isFromInputTarget(e) {
200
222
  const t = e?.target;
@@ -344,41 +366,44 @@ function isAltGraphCharacter(e) {
344
366
  function isComposingEvent(e) {
345
367
  return Boolean(e.isComposing || e.keyCode === 229);
346
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
+ }
347
402
  function handleEvent(type, phase = "all") {
348
403
  return (e) => {
349
404
  if (paused) return;
350
- const altGraphChar = isAltGraphCharacter(e);
351
- const composing = isComposingEvent(e);
352
- const fromInput = ignoreEditable && isFromInputTarget(e);
353
- const comboStr = comboKeyFromEvent(e);
354
- const codeStr = codeKeyFromEvent(e);
355
- const seen = /* @__PURE__ */ new Set();
356
- const candidates = [];
357
- for (const lookupKey of [comboStr, codeStr]) {
358
- if (!lookupKey || seen.has(lookupKey)) continue;
359
- seen.add(lookupKey);
360
- const bindings = registry.get(lookupKey)?.get(type);
361
- if (!bindings?.length) continue;
362
- for (const b of bindings) {
363
- const o2 = b.options;
364
- if (phase === "capture" && !o2.capture) continue;
365
- if (phase === "bubble" && o2.capture) continue;
366
- if (altGraphChar && !o2.altGraph) continue;
367
- if (composing && !o2.composing) continue;
368
- if (fromInput && !o2.allowIn?.(e)) continue;
369
- if (type === "keydown" && o2.repeat === false && e.repeat) continue;
370
- if (o2.when && o2.when(e) === false) continue;
371
- candidates.push(b);
372
- }
373
- }
374
- if (!candidates.length) return;
375
- const winner = pickWinner(candidates);
376
- const o = winner.options;
377
- if (o.preventDefault) e.preventDefault();
378
- if (o.stopImmediatePropagation) e.stopImmediatePropagation();
379
- else if (o.stopPropagation) e.stopPropagation();
380
- winner.handler(e);
381
- if (o.once) removeById(winner.id);
405
+ const candidates = eligibleBindings(e, type, phase);
406
+ if (candidates.length) fire(pickWinner(candidates), e);
382
407
  };
383
408
  }
384
409
  var stopDown = null;
@@ -417,13 +442,62 @@ var BARE_MOD_TO_KEY = {
417
442
  alt: "Alt",
418
443
  meta: "Meta"
419
444
  };
420
- function trigger(hotkeyStr, { type: forcedType } = {}) {
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 } = {}) {
421
496
  const { combo, type } = parseHotkey(hotkeyStr);
422
- const comboStr = comboKeyFromParts(combo);
423
497
  const actualType = forcedType || type;
424
- const bindings = registry.get(comboStr)?.get(actualType);
425
- if (!bindings?.length) return false;
426
- const eventKey = combo.bareModifier ? BARE_MOD_TO_KEY[combo.bareModifier] : combo.key;
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);
427
501
  let altKey = !!combo.alt;
428
502
  let ctrlKey = !!combo.ctrl;
429
503
  let shiftKey = !!combo.shift;
@@ -437,32 +511,33 @@ function trigger(hotkeyStr, { type: forcedType } = {}) {
437
511
  const e = {
438
512
  type: actualType,
439
513
  key: eventKey,
440
- code: combo.code || null,
514
+ code: eventCode,
441
515
  ctrlKey,
442
516
  shiftKey,
443
517
  altKey,
444
518
  metaKey,
445
519
  repeat: false,
520
+ isComposing: false,
521
+ getModifierState() {
522
+ return false;
523
+ },
446
524
  preventDefault() {
447
525
  },
448
526
  stopPropagation() {
449
527
  },
450
528
  stopImmediatePropagation() {
451
529
  },
452
- target: null
530
+ target
453
531
  };
454
- const winner = pickWinner(
455
- bindings.filter((b) => b.options.when ? b.options.when(e) !== false : true)
456
- );
457
- if (!winner) return false;
458
- winner.handler(e);
459
- if (winner.options.once) removeById(winner.id);
532
+ const candidates = eligibleBindings(e, actualType, "all");
533
+ if (!candidates.length) return false;
534
+ fire(pickWinner(candidates), e);
460
535
  return true;
461
536
  }
462
- function comboFromEvent(e, { physical = true, useMod = false } = {}) {
537
+ function comboFromEvent(e, { physical = true, useMod = false, platform = PLATFORM } = {}) {
463
538
  if (!e || MODIFIER_KEY_TOKEN[e.key]) return null;
464
539
  const parts = [];
465
- const primaryIsMeta = isMac;
540
+ const primaryIsMeta = platform === "mac";
466
541
  if (useMod && (primaryIsMeta ? e.metaKey : e.ctrlKey)) parts.push("mod");
467
542
  if (e.ctrlKey && !(useMod && !primaryIsMeta)) parts.push("ctrl");
468
543
  if (e.metaKey && !(useMod && primaryIsMeta)) parts.push("meta");
@@ -497,11 +572,13 @@ var hotkey_router_default = {
497
572
  trigger,
498
573
  // helpers
499
574
  parseHotkey,
500
- comboFromEvent
575
+ comboFromEvent,
576
+ detectPlatform
501
577
  };
502
578
  export {
503
579
  comboFromEvent,
504
580
  hotkey_router_default as default,
581
+ detectPlatform,
505
582
  parseHotkey
506
583
  };
507
584
  //# sourceMappingURL=hotkey-router.js.map