Created
October 13, 2020 06:32
-
-
Save metodribic/641afe6f5eeb3c9f6faf3574a08bb23d to your computer and use it in GitHub Desktop.
Utils for dealing with keyboard events and figuring out what was pressed
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
export const enum KeyCodes { | |
BACKSPACE = 8, | |
TAB = 9, | |
ENTER = 13, | |
SPACE = 32, | |
DELETE = 46 | |
} | |
export class EventUtil { | |
/** | |
* Util for checking if pressed key is number | |
*/ | |
static isNumberKey(key): boolean { | |
if (key >= 96 && key <= 105) { | |
// Num pad keys | |
key -= 48; | |
} | |
return key > 47 && key < 58; | |
} | |
/** | |
* Check if pressed key is arrow key | |
*/ | |
static isArrowKey(key: number): boolean { | |
return key > 36 && key < 41; | |
} | |
/** | |
* Check if press key is allowed | |
*/ | |
static isAllowedKeyType(event): boolean { | |
const keyCode = event.keyCode; | |
return event.metaKey || event.ctrlKey || | |
event.altKey || event.shiftKey || | |
keyCode === KeyCodes.TAB || | |
keyCode === KeyCodes.DELETE || | |
keyCode === KeyCodes.BACKSPACE || | |
keyCode === KeyCodes.ENTER; | |
} | |
/** | |
* Check if Delete or Backspace | |
*/ | |
static isRemoveKey(pressedKeyCode): boolean { | |
return pressedKeyCode === KeyCodes.DELETE || pressedKeyCode === KeyCodes.BACKSPACE; | |
} | |
/** | |
* Check if pressed button is control or command | |
*/ | |
static isMetaOrCtrlKey(event): boolean { | |
return event.metaKey || event.ctrlKey; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment