hotkey-router 0.5.1 → 0.6.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.
Files changed (42) hide show
  1. package/README.md +292 -670
  2. package/data/browser-hotkeys.json +40 -0
  3. package/data/site-hotkeys.json +1 -1
  4. package/data/site-hotkeys.runtime.json +1 -1
  5. package/dist/auto.js +3 -3
  6. package/dist/auto.js.map +2 -2
  7. package/dist/auto.min.js +2 -2
  8. package/dist/core.js +55 -324
  9. package/dist/core.js.map +3 -3
  10. package/dist/dev.js +56 -0
  11. package/dist/dev.js.map +7 -0
  12. package/dist/format.js +13 -178
  13. package/dist/format.js.map +3 -3
  14. package/dist/hotkey-router.cjs +69 -165
  15. package/dist/hotkey-router.cjs.map +3 -3
  16. package/dist/hotkey-router.js +1 -1
  17. package/dist/hotkey-router.js.map +2 -2
  18. package/dist/hotkey-router.min.js +2 -2
  19. package/dist/lookup.js +9 -0
  20. package/dist/lookup.js.map +7 -0
  21. package/dist/parse.js +207 -0
  22. package/dist/parse.js.map +7 -0
  23. package/dist/platform.js +42 -0
  24. package/dist/platform.js.map +7 -0
  25. package/dist/reservations.js +17 -533
  26. package/dist/reservations.js.map +3 -3
  27. package/dist/shifted-punctuation.js +34 -0
  28. package/dist/shifted-punctuation.js.map +7 -0
  29. package/dist/sites.js +4 -203
  30. package/dist/sites.js.map +3 -3
  31. package/dist/testing.js +104 -0
  32. package/dist/testing.js.map +7 -0
  33. package/dist/types/core.d.ts +3 -9
  34. package/dist/types/dev.d.ts +48 -0
  35. package/dist/types/lookup.d.ts +1 -0
  36. package/dist/types/parse.d.ts +0 -13
  37. package/dist/types/reservations.d.ts +14 -41
  38. package/dist/types/shifted-punctuation.d.ts +17 -0
  39. package/dist/types/testing.d.ts +17 -0
  40. package/dist/validate.js +11 -191
  41. package/dist/validate.js.map +3 -3
  42. package/package.json +9 -1
package/dist/core.js CHANGED
@@ -1,198 +1,10 @@
1
- // hotkey-router v0.5.1 | SEE LICENSE IN LICENSE
1
+ // hotkey-router v0.6.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
- var SHIFTED_PUNCT = {
169
- ",": ["<", "Comma"],
170
- ".": [">", "Period"],
171
- "/": ["?", "Slash"],
172
- ";": [":", "Semicolon"],
173
- "'": ['"', "Quote"],
174
- "[": ["{", "BracketLeft"],
175
- "]": ["}", "BracketRight"],
176
- "\\": ["|", "Backslash"],
177
- "-": ["_", "Minus"],
178
- "=": ["+", "Equal"],
179
- "`": ["~", "Backquote"]
180
- };
181
- function shiftedPunctuationHint(hotkeyStr) {
182
- const { combo, type, error } = readHotkey(hotkeyStr);
183
- if (error || !combo.shift || combo.code) return null;
184
- const shifted = SHIFTED_PUNCT[combo.key];
185
- if (!shifted) return null;
186
- const [typed, code] = shifted;
187
- const base = String(hotkeyStr).trim().replace(/\s+up$/i, "");
188
- const suggestion = base.slice(0, -1) + "code:" + code + (type === "keyup" ? " up" : "");
189
- return {
190
- message: `"${hotkeyStr}" never fires on US layouts: Shift turns "${combo.key}" into "${typed}". Bind "${suggestion}" instead.`,
191
- suggestion
192
- };
193
- }
194
-
195
4
  // core.js
5
+ import { ownValue } from "./lookup.js";
6
+ import { parseHotkey, normalizeKey } from "./parse.js";
7
+ import { detectPlatform } from "./platform.js";
196
8
  function on(target, type, fn, options) {
197
9
  target.addEventListener(type, fn, options);
198
10
  return () => target.removeEventListener(type, fn, options);
@@ -206,7 +18,6 @@ var MODIFIER_KEY_TOKEN = Object.freeze({
206
18
  Meta: "meta",
207
19
  OS: "meta"
208
20
  });
209
- var warnedShifted = /* @__PURE__ */ new Set();
210
21
  function comboKeyFromParts({ ctrl, shift, alt, meta, key, code, bareModifier }) {
211
22
  if (bareModifier) return `__bare__:${bareModifier}`;
212
23
  let s = "";
@@ -218,7 +29,7 @@ function comboKeyFromParts({ ctrl, shift, alt, meta, key, code, bareModifier })
218
29
  return s ? s + key : key;
219
30
  }
220
31
  function comboKeyFromEvent(e) {
221
- const bareMod = MODIFIER_KEY_TOKEN[e.key];
32
+ const bareMod = ownValue(MODIFIER_KEY_TOKEN, e.key);
222
33
  if (bareMod) return `__bare__:${bareMod}`;
223
34
  return comboKeyFromParts({
224
35
  ctrl: e.ctrlKey,
@@ -276,7 +87,12 @@ function focusKind(e, mode) {
276
87
  return null;
277
88
  }
278
89
  function isChordEvent(e) {
279
- return Boolean((e.ctrlKey || e.altKey || e.metaKey) && !MODIFIER_KEY_TOKEN[e.key]);
90
+ return Boolean((e.ctrlKey || e.altKey || e.metaKey) && !ownValue(MODIFIER_KEY_TOKEN, e.key));
91
+ }
92
+ function assertHandler(hotkeyStr, handler) {
93
+ if (typeof handler !== "function") {
94
+ throw new TypeError(`hotkeys.bind("${hotkeyStr}") expects a function handler, got ${handler === null ? "null" : typeof handler}`);
95
+ }
280
96
  }
281
97
  function inputMode(value) {
282
98
  if (value === "all" || value === "text") return value;
@@ -323,64 +139,19 @@ function latinKeyFromEvent(e) {
323
139
  key: letter[1].toLowerCase()
324
140
  });
325
141
  }
326
- var BARE_MOD_TO_KEY = {
327
- ctrl: "Control",
328
- shift: "Shift",
329
- alt: "Alt",
330
- meta: "Meta"
331
- };
332
- var CODE_TO_KEY = {
333
- Period: ".",
334
- Comma: ",",
335
- Semicolon: ";",
336
- Quote: "'",
337
- Slash: "/",
338
- Backslash: "\\",
339
- BracketLeft: "[",
340
- BracketRight: "]",
341
- Minus: "-",
342
- Equal: "=",
343
- Backquote: "`",
344
- Space: " ",
345
- Enter: "Enter",
346
- NumpadEnter: "Enter",
347
- Tab: "Tab",
348
- Escape: "Escape",
349
- Backspace: "Backspace",
350
- Delete: "Delete",
351
- Insert: "Insert",
352
- Home: "Home",
353
- End: "End",
354
- PageUp: "PageUp",
355
- PageDown: "PageDown",
356
- ArrowUp: "ArrowUp",
357
- ArrowDown: "ArrowDown",
358
- ArrowLeft: "ArrowLeft",
359
- ArrowRight: "ArrowRight"
360
- };
361
- var KEY_TO_CODE = {};
362
- var _a;
363
- for (const [code, key] of Object.entries(CODE_TO_KEY)) {
364
- KEY_TO_CODE[_a = normalizeKey(key)] ?? (KEY_TO_CODE[_a] = code);
365
- }
366
- function keyForCode(code) {
367
- if (!code) return null;
368
- const letter = /^Key([A-Z])$/.exec(code);
369
- if (letter) return letter[1].toLowerCase();
370
- const digit = /^(?:Digit|Numpad)(\d)$/.exec(code);
371
- if (digit) return digit[1];
372
- if (/^F\d{1,2}$/.test(code)) return code;
373
- return CODE_TO_KEY[code] ?? null;
374
- }
375
- function codeForKey(key) {
376
- if (!key) return null;
377
- if (/^[a-z]$/.test(key)) return "Key" + key.toUpperCase();
378
- if (/^\d$/.test(key)) return "Digit" + key;
379
- if (/^f\d{1,2}$/.test(key)) return key.toUpperCase();
380
- return KEY_TO_CODE[key] ?? null;
142
+ function unshiftedKeyFromEvent(e) {
143
+ if (!e.shiftKey || typeof e.key !== "string" || e.key.length !== 1) return null;
144
+ if (/\s/.test(e.key) || e.key.toLowerCase() !== e.key.toUpperCase()) return null;
145
+ return comboKeyFromParts({
146
+ ctrl: e.ctrlKey,
147
+ shift: false,
148
+ alt: e.altKey,
149
+ meta: e.metaKey,
150
+ key: normalizeKey(e.key)
151
+ });
381
152
  }
382
153
  function comboFromEvent(e, { physical = true, useMod = false, platform = PLATFORM } = {}) {
383
- if (!e || MODIFIER_KEY_TOKEN[e.key]) return null;
154
+ if (!e || ownValue(MODIFIER_KEY_TOKEN, e.key)) return null;
384
155
  const parts = [];
385
156
  const primaryIsMeta = platform === "mac";
386
157
  if (useMod && (primaryIsMeta ? e.metaKey : e.ctrlKey)) parts.push("mod");
@@ -442,6 +213,7 @@ function createRouter({
442
213
  }
443
214
  function bind(hotkeyStr, handler, plugin = null, options = {}) {
444
215
  const { combo, type, raw } = parseHotkey(hotkeyStr);
216
+ assertHandler(hotkeyStr, handler);
445
217
  const comboStr = comboKeyFromParts(combo);
446
218
  const opts = normalizeOptions(type, options);
447
219
  const binding = {
@@ -456,18 +228,10 @@ function createRouter({
456
228
  };
457
229
  ensureSlot(comboStr, type).push(binding);
458
230
  bindingIndex.set(binding.id, { comboStr, type });
459
- const warnKey = `${comboStr} ${type}`;
460
- if (!warnedShifted.has(warnKey)) {
461
- const hint = shiftedPunctuationHint(hotkeyStr);
462
- if (hint) {
463
- warnedShifted.add(warnKey);
464
- console.warn(`[hotkey-router] ${hint.message}`);
465
- }
466
- }
467
231
  if (bindHooks.length) {
468
232
  for (const hook of bindHooks) {
469
233
  try {
470
- hook({ combo, raw, options: opts, plugin, id: binding.id });
234
+ hook({ combo, type, raw, options: opts, plugin, id: binding.id });
471
235
  } catch (err) {
472
236
  console.error("[hotkey-router] onBind hook threw:", err);
473
237
  }
@@ -510,16 +274,21 @@ function createRouter({
510
274
  }
511
275
  function registerPlugin(name, hotkeyMap) {
512
276
  if (plugins.has(name)) throw new Error(`Plugin "${name}" already registered`);
513
- const entries = Object.entries(hotkeyMap);
514
- for (const [hotkeyStr] of entries) parseHotkey(hotkeyStr);
515
- const ids = [];
516
- for (const [hotkeyStr, fnOrTuple] of entries) {
277
+ const entries = Object.entries(hotkeyMap).map(([hotkeyStr, fnOrTuple]) => {
517
278
  const [fn, options] = Array.isArray(fnOrTuple) ? fnOrTuple : [fnOrTuple, {}];
279
+ parseHotkey(hotkeyStr);
280
+ assertHandler(hotkeyStr, fn);
281
+ return [hotkeyStr, fn, options];
282
+ });
283
+ const ids = [];
284
+ for (const [hotkeyStr, fn, options] of entries) {
518
285
  const off = bind(hotkeyStr, fn, name, options);
519
286
  ids.push(off.id);
520
287
  }
521
288
  plugins.set(name, ids);
522
- return () => unregisterPlugin(name);
289
+ return () => {
290
+ if (plugins.get(name) === ids) unregisterPlugin(name);
291
+ };
523
292
  }
524
293
  function unregisterPlugin(name) {
525
294
  const ids = plugins.get(name);
@@ -553,9 +322,13 @@ function createRouter({
553
322
  seen.add(lookupKey);
554
323
  collectEligible(candidates, lookupKey, e, type, phase, guards);
555
324
  }
556
- if (!candidates.length) {
557
- const latinKey = latinKeyFromEvent(e);
558
- if (latinKey && !seen.has(latinKey)) collectEligible(candidates, latinKey, e, type, phase, guards);
325
+ for (const fallback of [latinKeyFromEvent, unshiftedKeyFromEvent]) {
326
+ if (candidates.length) break;
327
+ const k = fallback(e);
328
+ if (k && !seen.has(k)) {
329
+ seen.add(k);
330
+ collectEligible(candidates, k, e, type, phase, guards);
331
+ }
559
332
  }
560
333
  return candidates;
561
334
  }
@@ -579,19 +352,24 @@ function createRouter({
579
352
  if (o.preventDefault) e.preventDefault();
580
353
  if (o.stopImmediatePropagation) e.stopImmediatePropagation();
581
354
  else if (o.stopPropagation) e.stopPropagation();
582
- try {
583
- winner.handler(e);
584
- } finally {
585
- if (o.once) removeById(winner.id);
586
- }
355
+ if (o.once) removeById(winner.id);
356
+ winner.handler(e);
357
+ }
358
+ function routeEvent(e, type, phase) {
359
+ if (paused) return false;
360
+ const candidates = eligibleBindings(e, type, phase);
361
+ if (!candidates.length) return false;
362
+ fire(pickWinner(candidates), e);
363
+ return true;
587
364
  }
588
365
  function handleEvent(type, phase = "all") {
589
366
  return (e) => {
590
- if (paused) return;
591
- const candidates = eligibleBindings(e, type, phase);
592
- if (candidates.length) fire(pickWinner(candidates), e);
367
+ routeEvent(e, type, phase);
593
368
  };
594
369
  }
370
+ function dispatch(e, type) {
371
+ return routeEvent(e, type, "all");
372
+ }
595
373
  let stopDown = null;
596
374
  let stopUp = null;
597
375
  let stopCaptureDown = null;
@@ -622,48 +400,6 @@ function createRouter({
622
400
  plugins.clear();
623
401
  bindingIndex.clear();
624
402
  }
625
- function trigger(hotkeyStr, { type: forcedType, target: target2 = null } = {}) {
626
- const { combo, type } = parseHotkey(hotkeyStr);
627
- const actualType = forcedType || type;
628
- if (paused) return false;
629
- const eventKey = combo.bareModifier ? BARE_MOD_TO_KEY[combo.bareModifier] : combo.key ?? keyForCode(combo.code);
630
- const eventCode = combo.bareModifier ? null : combo.code ?? codeForKey(combo.key);
631
- let altKey = !!combo.alt;
632
- let ctrlKey = !!combo.ctrl;
633
- let shiftKey = !!combo.shift;
634
- let metaKey = !!combo.meta;
635
- if (combo.bareModifier && actualType === "keyup") {
636
- if (combo.bareModifier === "alt") altKey = false;
637
- else if (combo.bareModifier === "ctrl") ctrlKey = false;
638
- else if (combo.bareModifier === "shift") shiftKey = false;
639
- else if (combo.bareModifier === "meta") metaKey = false;
640
- }
641
- const e = {
642
- type: actualType,
643
- key: eventKey,
644
- code: eventCode,
645
- ctrlKey,
646
- shiftKey,
647
- altKey,
648
- metaKey,
649
- repeat: false,
650
- isComposing: false,
651
- getModifierState() {
652
- return false;
653
- },
654
- preventDefault() {
655
- },
656
- stopPropagation() {
657
- },
658
- stopImmediatePropagation() {
659
- },
660
- target: target2
661
- };
662
- const candidates = eligibleBindings(e, actualType, "all");
663
- if (!candidates.length) return false;
664
- fire(pickWinner(candidates), e);
665
- return true;
666
- }
667
403
  return {
668
404
  // lifecycle
669
405
  init,
@@ -680,12 +416,7 @@ function createRouter({
680
416
  pause,
681
417
  resume,
682
418
  ignoreInput,
683
- // testing / automation
684
- trigger,
685
- // helpers
686
- parseHotkey,
687
- comboFromEvent,
688
- detectPlatform
419
+ dispatch
689
420
  };
690
421
  }
691
422
  export {