@binlf/onhotkey
v0.1.0
Published
Featherweight utility that lets you easily compose hotkey combinations and attach event listeners.
Downloads
40
Maintainers
Readme
onHotKey
Featherweight utility that lets you easily compose hotkey combinations and attach event listeners.
Goals
- Minimal to zero dependencies
- Framework agnostic and close to vanilla JavaScript
- Single public utility:
onHotKey() - ESM-only output
Install
bun add @binlf/onhotkeyAPI
import type { Key } from "ts-key-enum";
type HotKey = Key | "esc" | "return" | "space" | "spacebar" | `${string}`;
function onHotKey(
hotKey: HotKey | readonly HotKey[],
handler: (event: KeyboardEvent) => void,
): (event: KeyboardEvent) => void;onHotKey() returns an event handler wrapper that runs your callback when the key combo matches.
Combo format
- Single key:
"w","CapsLock","Escape" - Modifier + key:
"ctrl+k","meta+shift+p" - Modifier-only:
"ctrl+shift" - Multiple alternatives:
["ctrl+k", "meta+k"]
Supported modifier aliases:
control->ctrloption->altcmd,command,super->meta
Supported key aliases:
esc->Escapereturn->Enterspacebar," "->space
Usage
import { onHotKey } from "@binlf/onhotkey";
const handleInputW = (event: KeyboardEvent) => {
console.log("Pressed W", event.key);
};
const onKeyDown = onHotKey("w", handleInputW);Framework-style handler:
<input onKeyDown={onHotKey("w", handleInputW)} />Vanilla listener:
window.addEventListener("keydown", onHotKey("ctrl+k", (event) => {
event.preventDefault();
console.log("Open command menu");
}));Multiple combos:
window.addEventListener("keydown", onHotKey(["ctrl+k", "meta+k"], () => {
console.log("Cross-platform shortcut");
}));Type-safe key enums in TypeScript:
import { Key } from "ts-key-enum";
import { onHotKey } from "@binlf/onhotkey";
window.addEventListener("keydown", onHotKey(Key.Escape, () => {
console.log("escape");
}));Runtime behavior
- Matching is case-insensitive (
"W"matches"w"). - Modifier matching is exact in this draft (extra modifiers fail the match).
- Invalid combos throw
TypeErrorwith anonHotKey:prefix. - No implicit side effects: core does not call
preventDefault().
Why exact modifiers?
Exact matching keeps shortcut behavior predictable and avoids surprising collisions.
For example, "ctrl+k" will not also fire when Shift is pressed unless you explicitly include it.
Notes
- This package is ESM-only.
- Public API intentionally stays small and focused.
Development
bun run initializebun run build- Build ESM and declaration files intodist/bun run dev- Watch mode build with tsdownbun run test- Run runtime and type testsbun test tests/onHotKey.test.ts- Run a single test filebun test -t "supports key aliases"- Run tests by name patternbun run typecheck- Type-check source files
