Created
December 22, 2018 20:00
-
-
Save Sominemo/ff8d65baf08e7dfaa24a2973f2bca4d6 to your computer and use it in GitHub Desktop.
Original and docs: https://gist.github.com/Sominemo/54db02875a6e8a3710b9bf3ca5b9d789
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OnWordListener{constructor(e,s){this.parent=s,this.id=e}get info(){return this.parent.getById(this.id)}unset(){this.parent.unset(this.id)}}class OnWord{constructor(e=!1,s,t=!1,i=!1){this.register=[],this.disabled=!1,this.listener=this.handler.bind(this),document.addEventListener("keypress",this.listener),t&&this.listen(e,s,t,i)}listen(e,s,t=!1,i=!1){let r=this.register.findIndex(s=>s.string===e&&t===s.case&&i===s.debug);return-1===r?this.register.push({string:t?e:e.toLowerCase(),stage:0,callback:[s],case:t,debug:i}):this.register[r].callback.push(s),r=-1===r?this.register.length-1:r,new OnWordListener(r,this)}getById(e){return this.register[e]}handler(e){if(this.disabled)return;const{key:s}=e,t=s.toLowerCase();this.register.forEach(e=>{const i=e.case?s:t;e.string[e.stage]===i?(e.stage++,e.debug&&console.log(`${i} = ${e.string[e.stage-1]}`)):(e.debug&&console.log(`${i} != ${e.string[e.stage]}`),e.stage=0),e.stage>=e.string.length&&(e.stage=0,e.callback.forEach(e=>e()))})}unset(e){this.register.splice(e,1)}disable(e){this.disabled=!0,e&&(document.removeEventListener("keypress",this.listener),this.listener=!1)}enable(){this.disabled=!1,this.listener||(this.listener=this.handler.bind(this),document.addEventListener("keypress",this.listener))}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment