hotkey-matcher
v1.0.2
Published
Match a hotkey with dead simple implementation.
Maintainers
Readme
hotkey-matcher
Match a hotkey with dead simple implementation.
Usage
import hotkeyMatcher from "hotkey-matcher";
function pageHotkey(hotkey, fn) {
const ac = new AbortController();
window.addEventListener(
"keydown",
(e) => {
if (hotkeyMatcher(e, hotkey)) {
e.preventDefault();
e.stopImmediatePropagation();
// do anything you want
}
},
{ capture: true, signal: ac.signal }
);
return () => ac.abort();
}
pageHotkey("alt+ctrl+comma", () => {
// do anything you want
});Implementation
export default function hotkeyMatcher(e: KeyboardEvent, hotkey: string) {
const x = {
[`${e.key?.toLowerCase()}Key`]: true,
[`${e.code?.toLowerCase()}Key`]: true,
[`${e.code?.replace(/^(?:Key|Digit|Numpad)/, "").toLowerCase()}Key`]: true,
};
const conds = `meta+ctrl+alt+shift+${hotkey}`
.replace(/win|cmd|command|search/, "meta")
.replace(/control/, "ctrl")
.split("+")
.map((k) => k.toLowerCase().trim())
.map((k) => `${k}Key`)
.map((k, i) => [k, i >= 4 === !!(x[k] ?? (e as any)[k])]);
return Object.values(Object.fromEntries(conds)).every((ok) => ok);
}Development
To install dependencies:
bun installTo run:
bun run index.tsThis project was created using bun init in bun v1.1.21. Bun is a fast all-in-one JavaScript runtime.
License
Author: [email protected]
MIT
