UNPKG

@brr-dev/hotkey

Version:

A simple, lightweight library for binding hotkeys using Vanilla JS, with no external dependencies.

101 lines (99 loc) 2.93 kB
// src/isMacOS.ts var _userIsOnMac; function isMacOS() { var _a; if (_userIsOnMac === void 0) { if (navigator.userAgentData) { _userIsOnMac = navigator.userAgentData.platform === "macOS"; } else { _userIsOnMac = /mac/i.test( (_a = navigator.userAgent) != null ? _a : navigator.platform ); } } return _userIsOnMac; } // src/HotKeyMap.ts var _HotKeyMap = class extends Map { addHotKey(hotkey) { this._getCollectionForTarget(hotkey.target).add(hotkey); } removeHotKey(hotkey) { var _a; if (this.has(hotkey.target)) { (_a = this.get(hotkey.target)) == null ? void 0 : _a.delete(hotkey); } } _getCollectionForTarget(target) { let hotkeys; if (this.has(target)) { hotkeys = this.get(target); } else { hotkeys = /* @__PURE__ */ new Set(); this.set(target, hotkeys); this._registerEventHandler(target, hotkeys); } return hotkeys; } _registerEventHandler(target, hotkeys) { target.addEventListener("keydown", function(event) { hotkeys.forEach((hotkey) => { if (hotkey.satisfiesEvent(event)) { try { hotkey.callback(event); } catch (error) { console.warn("Failed to run HotKey"); console.error(error); } } }); }); } }; var HotKeyMap_default = new _HotKeyMap(); // src/HotKey.ts var HotKey = class { /** * Create a new HotKey binding with the given options. */ constructor(options) { var _a, _b, _c, _d; if (!options.callback) { throw new Error("Missing callback for new HotKey"); } if (!options.key) { throw new Error("Missing key for new HotKey"); } this.key = options.key; this.callback = options.callback; this.alt = (_a = options.alt) != null ? _a : false; this.ctrl = (_b = options.ctrl) != null ? _b : false; this.shift = (_c = options.shift) != null ? _c : false; this.target = (_d = options.target) != null ? _d : document.body; HotKeyMap_default.addHotKey(this); } unbind() { HotKeyMap_default.removeHotKey(this); } satisfiesEvent(event) { const isMac = isMacOS(); return this.key === _fixKeyCasing(event.key) && this.shift === event.shiftKey && // Check for the ctrlKey (Control) on Mac, altKey (Alt) on windows this.alt === (isMac ? event.ctrlKey : event.altKey) && // Check for the metaKey (Command) on Mac, ctrlKey (Ctrl) on windows this.ctrl === (isMac ? event.metaKey : event.ctrlKey); } toString() { let str = this.key; const isMac = isMacOS(); if (this.shift) str = "Shift + " + str; if (this.ctrl) str = (isMac ? "Cmd" : "Ctrl") + " + " + str; if (this.alt) str = (isMac ? "Ctrl" : "Alt") + " + " + str; return str; } }; function _fixKeyCasing(key) { return key.charAt(0).toUpperCase() + key.slice(1); } export { HotKey }; //# sourceMappingURL=index.mjs.map