Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

key-definitions

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

key-definitions

get a keyboard key definition from event

  • 2.0.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
120
decreased by-4%
Maintainers
1
Weekly downloads
 
Created
Source

npm version Known Vulnerabilities

About

Key-definitions module is made by one purpose: to have key definitions in one place. Key definitions are followed by MDN documentation and as recommended a web developers should check event.key on keyup event to detect pressed key (not a keydown event nor keyCode property). The reason for this read more in documentation.

Because there are numerous keyboard layouts this library is not 100% bulletproof.

Defined layouts follow QWERTY keyboards.

Usage

Before

const onKeyUpHandler = (event) => {
  if (event.keyCode === 65) {
    // this approach is deprecated by MDN
  }

  if (event.key === "ArrowLeft") {
    // check if pressed key is arrow left
  }

  if (event.key === " ") {
    // check if the key represents space
  }

  if (event.key === "A" || event.key === "B" || event.key === "C") {
    // check if event key is one of the
  }
};

useEffect(() => {
  document.addEventListener("keyup", onKeyUpHandler);

  return () => {
    document.removeEventListener("keyup", onKeyUpHandler);
  };
}, []);

Now

With new approach you can easily:

  • forward event instance to compare function
  • read a code easily by not memorizing what ASCII number means
import { UpperCase, ARROW_LEFT, SPACE } from "key-definitions";

const onKeyUpHandler = (event) => {
  if (compare(event, ARROW_LEFT)) {
    // you can check if given event represents space
  }

  if (event.key === ARROW_LEFT.key) {
    // you can check value by _key_ property
  }

  if (compare(event, [UpperCase.A, UpperCase.B, UpperCase.C])) {
    // check if any character is matching with event key
  }
};

useEffect(() => {
  document.addEventListener("keyup", onKeyUpHandler);

  return () => {
    document.removeEventListener("keyup", onKeyUpHandler);
  };
}, []);

Install

npm install key-definitions

or

yarn add key-definitions

Interfaces

Each key inherits KeyInterface that has following structure:

interface KeyInterface {
  keyCode: number | number[]; // event.keyCode, it can be an array in case when numerous supports for different operation systems exists
  keyCodeDefinitions?: KeyCodeSupportOS[]; // description of keyCode in case if multiple keyCode values exists
  hex?: hexNumber | hexNumber[]; // key's hex number, it's array if multiple keyCodeDefinitions exists
  code: string; // the same as event.code
  key: string; // the same as event.key
  isAltKey?: boolean;
  isMetaKey?: boolean;
  isShiftKey?: boolean;
  isCtrlKey?: boolean;
}

Functions

NameDescriptionReturn value
isCharacterDetect if pressed value is a character a-z and A-Z.boolean
comparecompare two values; compares key property and code in case of SHIFT, ALT and CONTROL keyboard eventsboolean

compare (value: KeyboardEvent, equalToValue: KeyInterface)

Compare event with key definitions from library.

import { SPACE } from "key-definitions";

const onKeyUp = (e: KeyboardEvent) => {
  compare(event, SPACE); // true
};

compare (value: KeyboardEvent, equalToValue: KeyInterface[])

Compare does event is one of the several key definitions from library.

import { SPACE, TAB } from "key-definitions";

const onKeyUp = (e: KeyboardEvent) => {
  compare(e.key, [SPACE, TAB]); // true
};

isCharacter (x: KeyboardEvent)

Function will check key, code or keyCode values of KeyboardEvent.

const onKeyUp = (e: KeyboardEvent) => {
  isCharacter(e); // you can forward KeyboardEvent to detect if pressed key is a character
};

document.addEventListener("keyup", onKeyUp);

isCharacter(x: string) => boolean

isCharacter("A"); // true
isCharacter("a"); // true
isCharacter("?"); // false
isCharacter("č"); // true
isCharacter("1"); // false
isCharacter("KeyA"); // true
isCharacter("KeyZ"); // true
isCharacter("Enter"); // false

isCharacter(x: number)

Even keyCode is deprecated it's still in usage by some developers. Forward keyCode value from keyup event.

isCharacter(64); // check 'a' value --> true
isCharacter(90); // check 'Z' value --> true
isCharacter(191); // check '?' value --> false
isCharacter(49); // check '1' value --> false

Supported table

Language layouts

LanguageLayoutFileName
EnglishUS-
CroatianCROLayout_CRO
GermanDELayout_DE

By default US layout is set, for different layout you need to import it independently.

import { LowerCase }, Layout_CRO, Layout_DE from "key-definitions";

console.log(LowerCase.A.key); // --> returns US layout --> value 'a'
console.log(Layout_CRO.LowerCase.A.key); // --> returns croatian layout --> value 'a'
console.log(Layout_CRO.LowerCase.Č.key); // --> returns croatian layout --> value 'č'
console.log(LowerCase.Č.key); // --> undefined (not supported for US layout)
console.log(Layout_DE.LowerCase.Ü.key); // --> returns german layout ---> value 'ü'
console.log(Layout_DE.LowerCase.UMLAUT_U.key); // --> returns german layout ---> value 'ü'

Sections

Alpha


Includes lower and upper case a-zA-Z.

KeyLayout
A-Zall
Čcro
Ćcro
Žcro
Đcro
Šcro
Ü (or UMLAUT_U)de
Ö (or UMLAUT_O)de
Ä (or UMLAUT_A)de
ẞ (or UMLAUT_S)de
import { LowerCase, UpperCase } from "key-definitions";

console.log(LowerCase.A.key); // --> returns value 'a'
console.log(UpperCase.A.key); // --> returns value 'A'

Digits


Includes all numerical keys 0-9 in alphanumeric keyboard section.

KeyName
0ZERO
1ONE
2TWO
3THREE
4FOUR
5FIVE
6SIX
7SEVEN
8EIGHT
9NINE
import { ZERO, SEVEN } from "key-definitions";

console.log(ZERO.key); // returns value '0'
console.log(SEVEN.key); // returns value '7'

Numpad


Includes all keys in numpad section - digits and general (functional keys such as enter, num lock). Example: 0-9, NumLock, Enter; We have two sections General (functional keys) and Digits (0-9 numbers).

KeyName
0-9ZERO-NINE
= (equal sign)EQUAL
enterENTER
arrow upARROW_UP
arrow downARROW_DOWN
arrow rightARROW_RIGHT
arrow leftARROW_LEFT
*MULTIPLY
+ADD
-SUBSTRACT
,COMMA
/DIVIDE
.DECIMAL
insertINSERT
endEND
page downPAGE_DOWN
homeHOME
page upPAGE_UP
deleteDELETE
import { Numpad } from "key-definitions";

console.log(Numpad.ARROW_DOWN.key); // returns value 'ArrowDown'
console.log(Numpad.ZERO.key); // returns '0'

Functions


Includes all keys from F1-F12 in function section.

import { F1 } from "key-definitions";

console.log(F1.key); // returns value 'F1'

Generics


Includes functional keys in alphanumeric keyboard section. Example: AltLeft, Shift, Enter, Tab, CapsLock.

KeyName
tabTAB
enterENTER
shift leftSHIFT_LEFT
shift rightSHIFT RIGHT
ctrl leftCTRL_LEFT
ctrl rightCTRL_RIGHT
alt leftALT_LEFT
alt rightALT_RIGHT
caps lockCAPS_LOCK
escapeESC
spaceSPACE
page upPAGE_UP
page downPAGE_DOWN
endEND
homeHOME
arrow leftARROW_LEFT
arrow upARROW_UP
arrow rightARROW_RIGHT
arrow downARROW_DOWN
print screenPRINT_SCREEN
insertINSERT
deleteDELETE
num lockNUM_LOCK
scroll lockSCROLL_LOCK
helpHELP
pausePAUSE
import { ALT_LEFT, ALT_RIGHT } from "key-definitions";

console.log(ALT_LEFT.key); // returns value 'Alt'
console.log(ALT_LEFT.code); // returns value 'AltLeft'
console.log(ALT_RIGHT.key); // returns 'Alt'
console.log(ALT_RIGHT.code); // returns 'AltRight'

Specials

Includes special keys like question marks )!?.$&%/#"\*) as part of alphanumeric keyboard section.

KeyName
!EXCLAMATION_MARK
"QUOTATION_MARK
#HASH
$DOLLAR_SIGN
%PERCENT
&AMPERSAND
'APOSTROPHE
(OPEN_PARENTHESIS
)CLOSE_PARENTHESIS
*ASTERISK
+PLUS
,COMMA
-DASH
.DOT
/SLASH
:COLON
;SEMICOLON
<LESS_THAN_BRACKET
=EQUAL
>GREATER_THAN_BRACKET
?QUESTION_MARK
@AMPERSAT
[OPEN_BRACKET
\BACKSLASH
]CLOSE_BRACKET
^CARET
_UNDERSCORE
`BACKQUOTE
{OPEN_BRACE
|VERTICAL_BAR
}CLOSE_BRACE
~TILDA
import { DOLLAR_SIGN } from "key-definitions";

console.log(DOLLAR_SIGN.key); // returns value '$'

Other resources:

https://keycode.info/for/!

https://www.computerhope.com/jargon/s/specchar.htm

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

Keywords

FAQs

Package last updated on 06 Oct 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc