UNPKG

@rwh/keystrokes

Version:

Keystrokes is an easy to use library for binding functions to keys and key combos. It can be used with any TypeScript or JavaScript project, even in non-browser environments.

1 lines • 12.4 kB
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.keystrokes={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t={addEventListener:(...e)=>{},removeEventListener:(...e)=>{},dispatchEvent:(...e)=>{}},n={userAgent:``},r=()=>typeof document<`u`?document:t,i=()=>typeof navigator<`u`?navigator:n,a=()=>i().userAgent.toLowerCase().includes(`mac`),o=!1,s=e=>{a()&&e.key===`Meta`&&(o=!0)},c=e=>{o&&e.key===`Meta`&&(o=!1,m())},l=[`Meta`,`Shift`,`Control`,`Alt`,`CapsLock`,`Tab`],u=e=>{o&&!l.includes(e.key)&&(p(e),r().dispatchEvent(new KeyboardEvent(`keyup`,{key:e.key,code:e.code,bubbles:!0,cancelable:!0})))},d=new Map,f=e=>{d.set(e.key,e)},p=e=>{d.delete(e.key)},m=()=>{for(let e of d.values()){let t=new KeyboardEvent(`keyup`,{key:e.key,code:e.code,bubbles:!0,cancelable:!0});r().dispatchEvent(t)}d.clear()},h=e=>{try{let t=()=>e();return addEventListener(`focus`,t),()=>{removeEventListener(`focus`,t)}}catch{}},g=e=>{try{let t=()=>{m(),e()};return addEventListener(`blur`,t),()=>removeEventListener(`blur`,t)}catch{}},_=e=>{try{let t=t=>{t.key&&(f(t),s(t),e({key:t.key,aliases:[`@${t.code}`],originalEvent:t,composedPath:()=>t.composedPath(),preventDefault:()=>t.preventDefault()}),u(t))};return r().addEventListener(`keydown`,t),()=>r().removeEventListener(`keydown`,t)}catch{}},v=e=>{try{let t=t=>{t.key&&(p(t),c(t),e({key:t.key,aliases:[`@${t.code}`],originalEvent:t,composedPath:()=>t.composedPath(),preventDefault:()=>t.preventDefault()}))};return r().addEventListener(`keyup`,t),()=>r().removeEventListener(`keyup`,t)}catch{}},y=class{_onPressed;_onPressedWithRepeat;_onReleased;_isPressed;_identity;constructor(e){this._isPressed=!1,this._identity=e,typeof e==`function`?this._onPressedWithRepeat=e:(this._onPressed=e.onPressed,this._onPressedWithRepeat=e.onPressedWithRepeat,this._onReleased=e.onReleased)}get isEmpty(){return!this._onPressed&&!this._onPressedWithRepeat&&!this._onReleased}isOwnHandler(e){return this._identity===e}executePressed(e){this._isPressed||this._onPressed?.(e),this._isPressed=!0,this._onPressedWithRepeat?.(e)}executeReleased(e){this._isPressed&&this._onReleased?.(e),this._isPressed=!1}},b=class e{static _parseCache={};static _normalizationCache={};static parseKeyCombo(t){if(e._parseCache[t])return e._parseCache[t];let n=t.toLowerCase(),r=``,i=[],a=[i],o=[a],s=[o],c=!1;for(let e=0;e<t.length;e+=1)if(n[e]===`\\`)c=!0;else if((n[e]===`+`||n[e]===`>`||n[e]===`,`)&&!c){if(r)throw Error(`cannot have two operators in a row`);r=n[e]}else n[e].match(/[^\s]/)&&(r&&=(r===`,`?(i=[],a=[i],o=[a],s.push(o)):r===`>`?(i=[],a=[i],o.push(a)):r===`+`&&(i=[],a.push(i)),``),c=!1,i.push(n[e]));let l=s.map(e=>e.map(e=>e.map(e=>e.join(``))));return e._parseCache[t]=l,l}static stringifyKeyCombo(e){return e.map(e=>e.map(e=>e.map(e=>e===`+`?`\\+`:e===`>`?`\\>`:e===`,`?`\\,`:e).join(`+`)).join(`>`)).join(`,`)}static normalizeKeyCombo(t){if(e._normalizationCache[t])return e._normalizationCache[t];let n=this.stringifyKeyCombo(this.parseKeyCombo(t));return e._normalizationCache[t]=n,n}get isPressed(){return!!this._isPressedWithFinalUnit}get sequenceIndex(){return this.isPressed?this._parsedKeyCombo.length:this._sequenceIndex}get sequenceLength(){return this._parsedKeyCombo.length}get isNewlyPressed(){return this._isNewlyPressed}get hasAdvancedSequence(){return this._hasAdvancedSequence}_normalizedKeyCombo;_parsedKeyCombo;_handlerState;_keyComboEventMapper;_movingToNextSequenceAt;_sequenceIndex;_unitIndex;_lastActiveKeyPresses;_lastActiveKeyCount;_isPressedWithFinalUnit;_isNewlyPressed;_hasAdvancedSequence;_isSuppressed;constructor(t,n,r={}){this._normalizedKeyCombo=e.normalizeKeyCombo(t),this._parsedKeyCombo=e.parseKeyCombo(t),this._handlerState=new y(r),this._keyComboEventMapper=n,this._movingToNextSequenceAt=0,this._sequenceIndex=0,this._unitIndex=0,this._lastActiveKeyPresses=[],this._lastActiveKeyCount=0,this._isPressedWithFinalUnit=null,this._isNewlyPressed=!1,this._hasAdvancedSequence=!1,this._isSuppressed=!1}isOwnHandler(e){return this._handlerState.isOwnHandler(e)}suppress(){this._isSuppressed=!0}executePressed(e){this._isSuppressed||(this._isPressedWithFinalUnit?.has(e.key)||e.aliases?.some(e=>this._isPressedWithFinalUnit?.has(e)))&&this._handlerState.executePressed(this._wrapEvent(this._lastActiveKeyPresses,{key:e.key,aliases:new Set(e.aliases),event:e}))}executeReleased(e){(this._isPressedWithFinalUnit?.has(e.key)||e.aliases?.some(e=>this._isPressedWithFinalUnit?.has(e)))&&(this._handlerState.executeReleased(this._wrapEvent(this._lastActiveKeyPresses,{key:e.key,aliases:new Set(e.aliases),event:e})),this._isPressedWithFinalUnit=null,this._isSuppressed=!1)}updateState(e,t){let n=e.length,r=n<this._lastActiveKeyCount;this._lastActiveKeyCount=n;let i=this._sequenceIndex>0||this._movingToNextSequenceAt!==0;this._isNewlyPressed=!1,this._hasAdvancedSequence=!1;let a=this._parsedKeyCombo[this._sequenceIndex],o=a.slice(0,this._unitIndex),s=a.slice(this._unitIndex),c=()=>{this._movingToNextSequenceAt=0,this._sequenceIndex=0,this._unitIndex=0,this._lastActiveKeyPresses.length=0,this._hasAdvancedSequence=!1,this._handlerState.isEmpty&&(this._isPressedWithFinalUnit=null)},l=0;if(r){if(this._movingToNextSequenceAt===0||this._movingToNextSequenceAt+t<Date.now())return c();if(n!==0)return;this._movingToNextSequenceAt=0,this._sequenceIndex+=1,this._unitIndex=0}else{for(let t of o){for(let n of t){let r=!1;for(let i=l;i<e.length&&i<l+t.length;i+=1)if(e[i].key===n||e[i].aliases.has(n)){r=!0;break}if(!r)return c()}l+=t.length}if(this._movingToNextSequenceAt===0){for(let t of s){for(let n of t){let r=!1;for(let i=l;i<e.length&&i<l+t.length;i+=1)if(e[i].key===n||e[i].aliases.has(n)){r=!0;break}if(!r)return}this._unitIndex+=1,l+=t.length,i&&(this._hasAdvancedSequence=!0)}if(l<n-1)return c();this._lastActiveKeyPresses[this._sequenceIndex]=e.slice(0),this._sequenceIndex<this._parsedKeyCombo.length-1?this._movingToNextSequenceAt=Date.now():(this._isNewlyPressed=!this._isPressedWithFinalUnit,this._isPressedWithFinalUnit=new Set(a[a.length-1]))}}}_wrapEvent(e,t){return{...this._keyComboEventMapper(e,t),keyCombo:this._normalizedKeyCombo,keyEvents:e.flat().map(e=>e.event),finalKeyEvent:t.event}}},x=1e3,S=class{sequenceTimeout;_isActive;_unbinder;_onActiveBinder;_onInactiveBinder;_onKeyPressedBinder;_onKeyReleasedBinder;_keyComboEventMapper;_selfReleasingKeys;_keyRemap;_handlerStates;_keyComboStates;_keyComboStatesArray;_activeKeyPresses;_activeKeyMap;_watchedKeyComboStates;constructor(e={}){this.sequenceTimeout=x,this._isActive=!0,this._onActiveBinder=()=>{},this._onInactiveBinder=()=>{},this._onKeyPressedBinder=()=>{},this._onKeyReleasedBinder=()=>{},this._keyComboEventMapper=()=>({}),this._selfReleasingKeys=[],this._keyRemap={},this._handlerStates={},this._keyComboStates={},this._keyComboStatesArray=[],this._activeKeyPresses=[],this._activeKeyMap=new Map,this._watchedKeyComboStates={},this.bindEnvironment(e)}get pressedKeys(){return this._activeKeyPresses.map(e=>e.key)}bindKey(e,t){if(typeof e==`object`){for(let n of e)this.bindKey(n,t);return}e=e.toLowerCase();let n=new y(t);this._handlerStates[e]??=[],this._handlerStates[e].push(n)}unbindKey(e,t){if(typeof e==`object`){for(let n of e)this.unbindKey(n,t);return}e=e.toLowerCase();let n=this._handlerStates[e];if(n){if(t)for(let e=0;e<n.length;e+=1)n[e].isOwnHandler(t)&&(n.splice(e,1),--e);else n.length=0}}bindKeyCombo(e,t){if(typeof e==`object`){for(let n of e)this.bindKeyCombo(n,t);return}e=b.normalizeKeyCombo(e);let n=new b(e,this._keyComboEventMapper,t);this._keyComboStates[e]??=[],this._keyComboStates[e].push(n),this._keyComboStatesArray.push(n)}unbindKeyCombo(e,t){if(typeof e==`object`){for(let n of e)this.unbindKeyCombo(n,t);return}e=b.normalizeKeyCombo(e);let n=this._keyComboStates[e];if(n){for(let e=0;e<n.length;e+=1)if(!t||n[e].isOwnHandler(t)){for(let t=0;t<this._keyComboStatesArray.length;t+=1)this._keyComboStatesArray[t]===n[e]&&(this._keyComboStatesArray.splice(t,1),--t);n.splice(e,1),--e}}}checkKey(e){return e=e.toLowerCase(),this._activeKeyPresses.some(t=>t.key===e||t.aliases.has(e))}checkKeyCombo(e){return this._ensureCachedKeyComboState(e).isPressed}checkKeyComboSequenceIndex(e){return this._ensureCachedKeyComboState(e).sequenceIndex}bindEnvironment(e={}){this.unbindEnvironment(),this._onActiveBinder=e.onActive??h,this._onInactiveBinder=e.onInactive??g,this._onKeyPressedBinder=e.onKeyPressed??_,this._onKeyReleasedBinder=e.onKeyReleased??v,this._keyComboEventMapper=e.mapKeyComboEvent??(()=>({})),this._selfReleasingKeys=e.selfReleasingKeys??[],this._keyRemap=e.keyRemap??{};let t=this._onActiveBinder(()=>{this._isActive=!0}),n=this._onInactiveBinder(()=>{this._isActive=!1}),r=this._onKeyPressedBinder(e=>{this._handleKeyPress(e)}),i=this._onKeyReleasedBinder(e=>{this._handleKeyRelease(e)});this._unbinder=()=>{t?.(),n?.(),r?.(),i?.()}}unbindEnvironment(){this._unbinder?.()}_ensureCachedKeyComboState(e){e=b.normalizeKeyCombo(e),this._watchedKeyComboStates[e]||(this._watchedKeyComboStates[e]=new b(e,this._keyComboEventMapper));let t=this._watchedKeyComboStates[e];return t.updateState(this._activeKeyPresses,this.sequenceTimeout),t}_handleKeyPress(e){if(!this._isActive)return;e={...e,key:e.key.toLowerCase(),aliases:e.aliases?.map(e=>e.toLowerCase())??[]};let t=this._keyRemap[e.key];t&&(e.key=t);for(let t=0;t<e.aliases.length;t+=1){let n=this._keyRemap[e.aliases[t]];n&&(e.aliases[t]=n)}let n=this._handlerStates[e.key];if(n)for(let t of n)t.executePressed(e);for(let t=0;t<e.aliases.length;t+=1){let n=this._handlerStates[e.aliases[t]];if(n)for(let t of n)t.executePressed(e)}let r=this._activeKeyMap.get(e.key);if(r)r.event=e;else{let t={key:e.key,aliases:new Set(e.aliases),event:e};this._activeKeyMap.set(e.key,t),this._activeKeyPresses.push(t)}this._updateKeyComboStates(),this._suppressOverlappedKeyCombos();for(let t of this._keyComboStatesArray)t.executePressed(e)}_handleKeyRelease(e){e={...e,key:e.key.toLowerCase(),aliases:e.aliases?.map(e=>e.toLowerCase())??[]};let t=this._keyRemap[e.key];if(t&&(e.key=t),e.aliases)for(let t=0;t<e.aliases.length;t+=1){let n=this._keyRemap[e.aliases[t]];n&&(e.aliases[t]=n)}let n=this._handlerStates[e.key];if(n)for(let t of n)t.executeReleased(e);for(let t=0;t<e.aliases.length;t+=1){let n=this._handlerStates[e.aliases[t]];if(n)for(let t of n)t.executeReleased(e)}if(this._activeKeyMap.has(e.key)){this._activeKeyMap.delete(e.key);for(let t=0;t<this._activeKeyPresses.length;t+=1)if(this._activeKeyPresses[t].key===e.key){this._activeKeyPresses.splice(t,1);break}}this._tryReleaseSelfReleasingKeys(),this._updateKeyComboStates();for(let t of this._keyComboStatesArray)t.executeReleased(e)}_updateKeyComboStates(){for(let e of this._keyComboStatesArray)e.updateState(this._activeKeyPresses,this.sequenceTimeout)}_suppressOverlappedKeyCombos(){let e=!1,t=0;for(let n of this._keyComboStatesArray)n.hasAdvancedSequence&&(e=!0,n.isPressed&&n.sequenceLength>t&&(t=n.sequenceLength));if(e)for(let e of this._keyComboStatesArray)e.isNewlyPressed&&(e.hasAdvancedSequence&&e.sequenceLength===t||e.suppress())}_tryReleaseSelfReleasingKeys(){for(let e of this._activeKeyPresses)for(let t of this._selfReleasingKeys)e.key===t&&this._handleKeyRelease(e.event)}},C,w,T=e=>{w=e??new S(C)},E=()=>(w||T(),w),D=e=>{C=e},O=(...e)=>E().bindKey(...e),k=(...e)=>E().unbindKey(...e),A=(...e)=>E().bindKeyCombo(...e),j=(...e)=>E().unbindKeyCombo(...e),M=(...e)=>E().checkKey(...e),N=(...e)=>E().checkKeyCombo(...e),P=b.normalizeKeyCombo,F=b.stringifyKeyCombo,I=b.parseKeyCombo;e.HandlerState=y,e.KeyComboState=b,e.Keystrokes=S,e.bindKey=O,e.bindKeyCombo=A,e.browserOnActiveBinder=h,e.browserOnInactiveBinder=g,e.browserOnKeyPressedBinder=_,e.browserOnKeyReleasedBinder=v,e.checkKey=M,e.checkKeyCombo=N,e.createTestKeystrokes=(e={})=>{let t,n,r,i;return Object.assign(new S({...e,onActive(e){t=e},onInactive(e){n=e},onKeyPressed(e){r=e},onKeyReleased(e){i=e}}),{activate(){t()},deactivate(){n()},press(e){r({composedPath:()=>[],preventDefault:()=>{},...e})},release(e){i({composedPath:()=>[],preventDefault:()=>{},...e})}})},e.defaultSequenceTimeout=x,e.getGlobalKeystrokes=E,e.normalizeKeyCombo=P,e.parseKeyCombo=I,e.setGlobalKeystrokes=T,e.setGlobalKeystrokesOptions=D,e.stringifyKeyCombo=F,e.unbindKey=k,e.unbindKeyCombo=j});