UNPKG

just-hotkeys

Version:

A declarative keyboard shortcut manager for JavaScript and TypeScript - framework agnostic with React support

166 lines (165 loc) 3.31 kB
const y = { // Special keys space: " ", enter: "Enter", return: "Enter", tab: "Tab", esc: "Escape", escape: "Escape", backspace: "Backspace", delete: "Delete", del: "Delete", // Arrow keys up: "ArrowUp", down: "ArrowDown", left: "ArrowLeft", right: "ArrowRight", // Function keys f1: "F1", f2: "F2", f3: "F3", f4: "F4", f5: "F5", f6: "F6", f7: "F7", f8: "F8", f9: "F9", f10: "F10", f11: "F11", f12: "F12", // Numbers 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9" }, k = { cmd: "meta", command: "meta", win: "meta", windows: "meta", option: "alt", opt: "alt", control: "ctrl" }; function l(r) { const t = r.toLowerCase().split("+").map((o) => o.trim()), e = { key: "", ctrl: !1, meta: !1, alt: !1, shift: !1 }; for (const o of t) { const a = k[o] || o; switch (a) { case "ctrl": e.ctrl = !0; break; case "meta": e.meta = !0; break; case "alt": e.alt = !0; break; case "shift": e.shift = !0; break; default: e.key = y[a] || a.toUpperCase(); break; } } return e; } function b(r, t) { const e = r.metaKey, o = r.ctrlKey; if (t.meta !== e || t.ctrl !== o || t.alt !== r.altKey || t.shift !== r.shiftKey) return !1; const a = r.key === " " ? " " : r.key; return a.toLowerCase() === t.key.toLowerCase() || a === t.key; } function f(r) { const t = l(r), e = []; return t.ctrl && e.push("ctrl"), t.meta && e.push("cmd"), t.alt && e.push("alt"), t.shift && e.push("shift"), e.push(t.key.toLowerCase()), e.join("+"); } const g = { target: globalThis.document || globalThis, preventDefault: !0, stopPropagation: !1, enableInInputs: !1 }; function w(r) { if (!r || typeof r.tagName != "string") return !1; const t = r, e = t.tagName.toLowerCase(); return e === "input" || e === "textarea" || e === "select" || t.contentEditable === "true"; } function F(r, t = {}) { const e = t.target || globalThis.document || globalThis, o = { ...g, ...t, target: e }, a = /* @__PURE__ */ new Map(); for (const [n, s] of Object.entries(r)) { const c = f(n); a.set(c, { parsed: l(n), callback: s }); } function i(n) { if (!(!o.enableInInputs && w(n.target))) { for (const [, { parsed: s, callback: c }] of a) if (b(n, s)) { o.preventDefault && n.preventDefault(), o.stopPropagation && n.stopPropagation(), c(n); break; } } } o.target.addEventListener("keydown", i); function u(n) { for (const [s, c] of Object.entries(n)) { const h = f(s); a.set(h, { parsed: l(s), callback: c }); } } function p(n) { for (const s of n) { const c = f(s); a.delete(c); } } function m() { o.target.removeEventListener( "keydown", i ), a.clear(); } function d() { return Array.from(a.keys()); } return { add: u, remove: p, destroy: m, getActiveShortcuts: d }; } function E(r, t) { return F(r, t).destroy; } export { F as createShortcuts, b as matchesShortcut, f as normalizeShortcut, l as parseShortcut, E as shortcuts };