hotkey-router 0.3.3 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js ADDED
@@ -0,0 +1,697 @@
1
+ // hotkey-router v0.4.1 | SEE LICENSE IN LICENSE
2
+
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
+ // core.js
196
+ function on(target, type, fn, options) {
197
+ target.addEventListener(type, fn, options);
198
+ return () => target.removeEventListener(type, fn, options);
199
+ }
200
+ var PLATFORM = detectPlatform();
201
+ var MODIFIER_KEY_TOKEN = Object.freeze({
202
+ Alt: "alt",
203
+ AltGraph: "alt",
204
+ Control: "ctrl",
205
+ Shift: "shift",
206
+ Meta: "meta",
207
+ OS: "meta"
208
+ });
209
+ var warnedShifted = /* @__PURE__ */ new Set();
210
+ function comboKeyFromParts({ ctrl, shift, alt, meta, key, code, bareModifier }) {
211
+ if (bareModifier) return `__bare__:${bareModifier}`;
212
+ let s = "";
213
+ if (ctrl) s += "ctrl+";
214
+ if (shift) s += "shift+";
215
+ if (alt) s += "alt+";
216
+ if (meta) s += "meta+";
217
+ if (code) return s + "code:" + code;
218
+ return s ? s + key : key;
219
+ }
220
+ function comboKeyFromEvent(e) {
221
+ const bareMod = MODIFIER_KEY_TOKEN[e.key];
222
+ if (bareMod) return `__bare__:${bareMod}`;
223
+ return comboKeyFromParts({
224
+ ctrl: e.ctrlKey,
225
+ shift: e.shiftKey,
226
+ alt: e.altKey,
227
+ meta: e.metaKey,
228
+ key: normalizeKey(e.key)
229
+ });
230
+ }
231
+ function codeKeyFromEvent(e) {
232
+ if (!e.code) return null;
233
+ let s = "";
234
+ if (e.ctrlKey) s += "ctrl+";
235
+ if (e.shiftKey) s += "shift+";
236
+ if (e.altKey) s += "alt+";
237
+ if (e.metaKey) s += "meta+";
238
+ return s + "code:" + e.code;
239
+ }
240
+ var CONTROL_INPUT_TYPES = /* @__PURE__ */ new Set([
241
+ "checkbox",
242
+ "radio",
243
+ "range",
244
+ "color",
245
+ "file",
246
+ "button",
247
+ "submit",
248
+ "reset",
249
+ "image"
250
+ ]);
251
+ function eventPath(e) {
252
+ const path = e?.composedPath?.();
253
+ if (path?.length) return path;
254
+ const out = [];
255
+ for (let n = e?.target; n; n = n.parentNode || n.host) out.push(n);
256
+ return out;
257
+ }
258
+ function focusKind(e, mode) {
259
+ const path = eventPath(e);
260
+ const t = path[0];
261
+ if (!t) return null;
262
+ const tag = String(t.tagName || "").toUpperCase();
263
+ if (t.isContentEditable || tag === "TEXTAREA" || tag === "SELECT" || t.getAttribute?.("role") === "textbox") {
264
+ return "text";
265
+ }
266
+ if (tag === "INPUT") {
267
+ if (mode === "all") return "text";
268
+ const type = String(t.getAttribute?.("type") || "text").toLowerCase();
269
+ return CONTROL_INPUT_TYPES.has(type) ? "control" : "text";
270
+ }
271
+ if (mode === "text") {
272
+ for (const el of path) {
273
+ if (String(el.tagName || "").toUpperCase() === "BUTTON" || el.getAttribute?.("role") === "button") return "control";
274
+ }
275
+ }
276
+ return null;
277
+ }
278
+ function isChordEvent(e) {
279
+ return Boolean((e.ctrlKey || e.altKey || e.metaKey) && !MODIFIER_KEY_TOKEN[e.key]);
280
+ }
281
+ function inputMode(value) {
282
+ if (value === "all" || value === "text") return value;
283
+ if (typeof value === "string") {
284
+ throw new TypeError(`hotkeys.ignoreInput() expects true, false, 'all' or 'text', got "${value}"`);
285
+ }
286
+ return value ? "all" : null;
287
+ }
288
+ function normalizeOptions(type, options) {
289
+ const o = options ? { ...options } : {};
290
+ if (type === "keydown" && o.repeat == null) o.repeat = false;
291
+ if (o.priority == null) o.priority = 0;
292
+ return o;
293
+ }
294
+ function pickWinner(bindings) {
295
+ let best = null;
296
+ for (const b of bindings) {
297
+ if (!best) best = b;
298
+ else if (b.options.priority > best.options.priority) best = b;
299
+ else if (b.options.priority === best.options.priority && b.id > best.id) best = b;
300
+ }
301
+ return best;
302
+ }
303
+ function isAltGraphCharacter(e) {
304
+ return Boolean(
305
+ e.ctrlKey && e.altKey && typeof e.getModifierState === "function" && e.getModifierState("AltGraph") && typeof e.key === "string" && e.key.length === 1
306
+ );
307
+ }
308
+ function isComposingEvent(e) {
309
+ return Boolean(e.isComposing || e.keyCode === 229);
310
+ }
311
+ var NON_LATIN_LETTER = /^(?!\p{Script=Latin})\p{L}$/u;
312
+ function latinKeyFromEvent(e) {
313
+ if (!(e.ctrlKey || e.metaKey) || e.altKey) return null;
314
+ if (isComposingEvent(e)) return null;
315
+ if (typeof e.getModifierState === "function" && e.getModifierState("AltGraph")) return null;
316
+ const letter = /^Key([A-Z])$/.exec(e.code || "");
317
+ if (!letter || typeof e.key !== "string" || !NON_LATIN_LETTER.test(e.key)) return null;
318
+ return comboKeyFromParts({
319
+ ctrl: e.ctrlKey,
320
+ shift: e.shiftKey,
321
+ alt: false,
322
+ meta: e.metaKey,
323
+ key: letter[1].toLowerCase()
324
+ });
325
+ }
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;
381
+ }
382
+ function comboFromEvent(e, { physical = true, useMod = false, platform = PLATFORM } = {}) {
383
+ if (!e || MODIFIER_KEY_TOKEN[e.key]) return null;
384
+ const parts = [];
385
+ const primaryIsMeta = platform === "mac";
386
+ if (useMod && (primaryIsMeta ? e.metaKey : e.ctrlKey)) parts.push("mod");
387
+ if (e.ctrlKey && !(useMod && !primaryIsMeta)) parts.push("ctrl");
388
+ if (e.metaKey && !(useMod && primaryIsMeta)) parts.push("meta");
389
+ if (e.altKey) parts.push("alt");
390
+ if (e.shiftKey) parts.push("shift");
391
+ if (physical && e.code) parts.push(`code:${e.code}`);
392
+ else {
393
+ const key = normalizeKey(e.key);
394
+ if (!key) return null;
395
+ parts.push(key === " " ? "space" : key);
396
+ }
397
+ return parts.join("+");
398
+ }
399
+ function createRouter({
400
+ target = typeof window !== "undefined" ? window : null,
401
+ capture = false,
402
+ ignoreInput: ignoreInputOption = true
403
+ } = {}) {
404
+ let focusMode = inputMode(ignoreInputOption);
405
+ let defaultTarget = target;
406
+ const defaultCapture = capture;
407
+ let bindHooks = [];
408
+ const registry = /* @__PURE__ */ new Map();
409
+ const plugins = /* @__PURE__ */ new Map();
410
+ const bindingIndex = /* @__PURE__ */ new Map();
411
+ let paused = false;
412
+ let nextId = 1;
413
+ function ensureSlot(comboStr, type) {
414
+ let typeMap = registry.get(comboStr);
415
+ if (!typeMap) {
416
+ typeMap = /* @__PURE__ */ new Map();
417
+ registry.set(comboStr, typeMap);
418
+ }
419
+ let arr = typeMap.get(type);
420
+ if (!arr) {
421
+ arr = [];
422
+ typeMap.set(type, arr);
423
+ }
424
+ return arr;
425
+ }
426
+ function removeById(id) {
427
+ const idx = bindingIndex.get(id);
428
+ if (!idx) return false;
429
+ const { comboStr, type } = idx;
430
+ const typeMap = registry.get(comboStr);
431
+ const arr = typeMap?.get(type);
432
+ if (!arr?.length) {
433
+ bindingIndex.delete(id);
434
+ return false;
435
+ }
436
+ const next = arr.filter((b) => b.id !== id);
437
+ if (next.length) typeMap.set(type, next);
438
+ else typeMap.delete(type);
439
+ if (!typeMap.size) registry.delete(comboStr);
440
+ bindingIndex.delete(id);
441
+ return true;
442
+ }
443
+ function bind(hotkeyStr, handler, plugin = null, options = {}) {
444
+ const { combo, type, raw } = parseHotkey(hotkeyStr);
445
+ const comboStr = comboKeyFromParts(combo);
446
+ const opts = normalizeOptions(type, options);
447
+ const binding = {
448
+ id: nextId++,
449
+ comboStr,
450
+ type,
451
+ combo,
452
+ handler,
453
+ plugin,
454
+ raw,
455
+ options: opts
456
+ };
457
+ ensureSlot(comboStr, type).push(binding);
458
+ 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
+ if (bindHooks.length) {
468
+ for (const hook of bindHooks) {
469
+ try {
470
+ hook({ combo, raw, options: opts, plugin, id: binding.id });
471
+ } catch (err) {
472
+ console.error("[hotkey-router] onBind hook threw:", err);
473
+ }
474
+ }
475
+ }
476
+ const off = () => removeById(binding.id);
477
+ off.id = binding.id;
478
+ off.hotkey = raw;
479
+ return off;
480
+ }
481
+ function onBind(hook) {
482
+ if (typeof hook !== "function") {
483
+ throw new TypeError("hotkeys.onBind(hook) expects a function");
484
+ }
485
+ bindHooks.push(hook);
486
+ return () => {
487
+ bindHooks = bindHooks.filter((h) => h !== hook);
488
+ };
489
+ }
490
+ function unbind(hotkeyStr, handler) {
491
+ const { combo, type } = parseHotkey(hotkeyStr);
492
+ const comboStr = comboKeyFromParts(combo);
493
+ const typeMap = registry.get(comboStr);
494
+ if (!typeMap) return;
495
+ const arr = typeMap.get(type);
496
+ if (!arr?.length) return;
497
+ if (!handler) {
498
+ for (const b of arr) bindingIndex.delete(b.id);
499
+ typeMap.delete(type);
500
+ } else {
501
+ const keep = [];
502
+ for (const b of arr) {
503
+ if (b.handler === handler) bindingIndex.delete(b.id);
504
+ else keep.push(b);
505
+ }
506
+ if (keep.length) typeMap.set(type, keep);
507
+ else typeMap.delete(type);
508
+ }
509
+ if (!typeMap.size) registry.delete(comboStr);
510
+ }
511
+ function registerPlugin(name, hotkeyMap) {
512
+ 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) {
517
+ const [fn, options] = Array.isArray(fnOrTuple) ? fnOrTuple : [fnOrTuple, {}];
518
+ const off = bind(hotkeyStr, fn, name, options);
519
+ ids.push(off.id);
520
+ }
521
+ plugins.set(name, ids);
522
+ return () => unregisterPlugin(name);
523
+ }
524
+ function unregisterPlugin(name) {
525
+ const ids = plugins.get(name);
526
+ if (!ids) return;
527
+ for (const id of ids) removeById(id);
528
+ plugins.delete(name);
529
+ }
530
+ function pause() {
531
+ paused = true;
532
+ }
533
+ function resume() {
534
+ paused = false;
535
+ }
536
+ function ignoreInput(value = true) {
537
+ focusMode = inputMode(value);
538
+ }
539
+ function setTarget(target2) {
540
+ defaultTarget = target2;
541
+ }
542
+ function eligibleBindings(e, type, phase) {
543
+ const guards = {
544
+ altGraphChar: isAltGraphCharacter(e),
545
+ composing: isComposingEvent(e),
546
+ focus: focusMode && focusKind(e, focusMode),
547
+ chord: isChordEvent(e)
548
+ };
549
+ const candidates = [];
550
+ const seen = /* @__PURE__ */ new Set();
551
+ for (const lookupKey of [comboKeyFromEvent(e), codeKeyFromEvent(e)]) {
552
+ if (!lookupKey || seen.has(lookupKey)) continue;
553
+ seen.add(lookupKey);
554
+ collectEligible(candidates, lookupKey, e, type, phase, guards);
555
+ }
556
+ if (!candidates.length) {
557
+ const latinKey = latinKeyFromEvent(e);
558
+ if (latinKey && !seen.has(latinKey)) collectEligible(candidates, latinKey, e, type, phase, guards);
559
+ }
560
+ return candidates;
561
+ }
562
+ function collectEligible(candidates, lookupKey, e, type, phase, { altGraphChar, composing, focus, chord }) {
563
+ const bindings = registry.get(lookupKey)?.get(type);
564
+ if (!bindings?.length) return;
565
+ for (const b of bindings) {
566
+ const o = b.options;
567
+ if (phase === "capture" && !o.capture) continue;
568
+ if (phase === "bubble" && o.capture) continue;
569
+ if (altGraphChar && !o.altGraph) continue;
570
+ if (composing && !o.composing) continue;
571
+ if (focus && !(focus === "control" && chord) && !o.allowIn?.(e)) continue;
572
+ if (type === "keydown" && o.repeat === false && e.repeat) continue;
573
+ if (o.when && o.when(e) === false) continue;
574
+ candidates.push(b);
575
+ }
576
+ }
577
+ function fire(winner, e) {
578
+ const o = winner.options;
579
+ if (o.preventDefault) e.preventDefault();
580
+ if (o.stopImmediatePropagation) e.stopImmediatePropagation();
581
+ else if (o.stopPropagation) e.stopPropagation();
582
+ try {
583
+ winner.handler(e);
584
+ } finally {
585
+ if (o.once) removeById(winner.id);
586
+ }
587
+ }
588
+ function handleEvent(type, phase = "all") {
589
+ return (e) => {
590
+ if (paused) return;
591
+ const candidates = eligibleBindings(e, type, phase);
592
+ if (candidates.length) fire(pickWinner(candidates), e);
593
+ };
594
+ }
595
+ let stopDown = null;
596
+ let stopUp = null;
597
+ let stopCaptureDown = null;
598
+ let stopCaptureUp = null;
599
+ function init({ target: target2 = defaultTarget, capture: capture2 = defaultCapture } = {}) {
600
+ if (!target2) throw new Error("hotkeys.init() requires a target (e.g. window)");
601
+ if (stopDown || stopUp) destroy();
602
+ if (capture2) {
603
+ stopDown = on(target2, "keydown", handleEvent("keydown"), { capture: true });
604
+ stopUp = on(target2, "keyup", handleEvent("keyup"), { capture: true });
605
+ return;
606
+ }
607
+ stopDown = on(target2, "keydown", handleEvent("keydown", "bubble"), { capture: false });
608
+ stopUp = on(target2, "keyup", handleEvent("keyup", "bubble"), { capture: false });
609
+ stopCaptureDown = on(target2, "keydown", handleEvent("keydown", "capture"), { capture: true });
610
+ stopCaptureUp = on(target2, "keyup", handleEvent("keyup", "capture"), { capture: true });
611
+ }
612
+ function destroy() {
613
+ stopDown?.();
614
+ stopUp?.();
615
+ stopCaptureDown?.();
616
+ stopCaptureUp?.();
617
+ stopDown = null;
618
+ stopUp = null;
619
+ stopCaptureDown = null;
620
+ stopCaptureUp = null;
621
+ registry.clear();
622
+ plugins.clear();
623
+ bindingIndex.clear();
624
+ }
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
+ return {
668
+ // lifecycle
669
+ init,
670
+ destroy,
671
+ setTarget,
672
+ // bindings
673
+ bind,
674
+ unbind,
675
+ registerPlugin,
676
+ unregisterPlugin,
677
+ // extension hooks
678
+ onBind,
679
+ // control
680
+ pause,
681
+ resume,
682
+ ignoreInput,
683
+ // testing / automation
684
+ trigger,
685
+ // helpers
686
+ parseHotkey,
687
+ comboFromEvent,
688
+ detectPlatform
689
+ };
690
+ }
691
+ export {
692
+ comboFromEvent,
693
+ createRouter,
694
+ detectPlatform,
695
+ parseHotkey
696
+ };
697
+ //# sourceMappingURL=core.js.map