-
Notifications
You must be signed in to change notification settings - Fork 0
/
keymap.min.js
1 lines (1 loc) · 1.65 KB
/
keymap.min.js
1
class KeyboardMapper{constructor(){this.keyMappings=new Map,this.activeKeys=new Set,this.activeCodes=new Set,this.ignoreInputs=["INPUT","SELECT","TEXTAREA"],this.scope="default",document.addEventListener("keydown",this.handleKeyDown.bind(this)),document.addEventListener("keyup",this.handleKeyUp.bind(this))}mapCombination(e,t,s="default"){if("string"!=typeof e||"function"!=typeof t)return void console.error("Invalid combination or callback");e.split(",").map((e=>e.trim().toLowerCase())).forEach((e=>{this.keyMappings.has(e)||this.keyMappings.set(e,[]);this.keyMappings.get(e).push({callback:t,scope:s})}))}unmapCombination(e){const t=e.toLowerCase();this.keyMappings.delete(t)}handleKeyDown(e){if(this.ignoreInputs.includes(e.target.tagName))return;const t=this.getKeyFromEvent(e);this.activeCodes.add(t.codes[0]),this.activeKeys.add(t.result[0]),this.executeCallbacks(e)}handleKeyUp(e){this.getKeyFromEvent(e);this.activeKeys.clear(),this.activeCodes.clear()}executeCallbacks(e){const t=Array.from(this.activeKeys),s=Array.from(this.activeCodes);t.join("+"),s.join("+");this.keyMappings.forEach(((o,i)=>{const a=i.split("+");(t.length===a.length&&a.every((e=>t.includes(e)))||s.length===a.length&&a.every((e=>s.includes(e))))&&(e.preventDefault(),o.forEach((e=>{const{callback:t,scope:s}=e;if("function"==typeof t){this.getScope()!==s&&"default"!==s||t()}})))}))}getKeyFromEvent(e){const{code:t,key:s,shiftKey:o,ctrlKey:i,altKey:a,metaKey:n}=e;let c=[],r=[];return"meta"==s.toLowerCase()||"control"==s.toLowerCase()?(c.push("ctrl"),r.push(t.toLowerCase())):(r.push(t.toLowerCase()),c.push(s.toLowerCase())),{codes:r,result:c}}getScope(){return this.scope}setScope(e){this.scope=e}}