UNPKG

2.75 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2013-present, Facebook, Inc.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 */
8
9'use strict';
10
11var getEventCharCode = require('./getEventCharCode');
12
13/**
14 * Normalization of deprecated HTML5 `key` values
15 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
16 */
17var normalizeKey = {
18 Esc: 'Escape',
19 Spacebar: ' ',
20 Left: 'ArrowLeft',
21 Up: 'ArrowUp',
22 Right: 'ArrowRight',
23 Down: 'ArrowDown',
24 Del: 'Delete',
25 Win: 'OS',
26 Menu: 'ContextMenu',
27 Apps: 'ContextMenu',
28 Scroll: 'ScrollLock',
29 MozPrintableKey: 'Unidentified'
30};
31
32/**
33 * Translation from legacy `keyCode` to HTML5 `key`
34 * Only special keys supported, all others depend on keyboard layout or browser
35 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
36 */
37var translateToKey = {
38 8: 'Backspace',
39 9: 'Tab',
40 12: 'Clear',
41 13: 'Enter',
42 16: 'Shift',
43 17: 'Control',
44 18: 'Alt',
45 19: 'Pause',
46 20: 'CapsLock',
47 27: 'Escape',
48 32: ' ',
49 33: 'PageUp',
50 34: 'PageDown',
51 35: 'End',
52 36: 'Home',
53 37: 'ArrowLeft',
54 38: 'ArrowUp',
55 39: 'ArrowRight',
56 40: 'ArrowDown',
57 45: 'Insert',
58 46: 'Delete',
59 112: 'F1',
60 113: 'F2',
61 114: 'F3',
62 115: 'F4',
63 116: 'F5',
64 117: 'F6',
65 118: 'F7',
66 119: 'F8',
67 120: 'F9',
68 121: 'F10',
69 122: 'F11',
70 123: 'F12',
71 144: 'NumLock',
72 145: 'ScrollLock',
73 224: 'Meta'
74};
75
76/**
77 * @param {object} nativeEvent Native browser event.
78 * @return {string} Normalized `key` property.
79 */
80function getEventKey(nativeEvent) {
81 if (nativeEvent.key) {
82 // Normalize inconsistent values reported by browsers due to
83 // implementations of a working draft specification.
84
85 // FireFox implements `key` but returns `MozPrintableKey` for all
86 // printable characters (normalized to `Unidentified`), ignore it.
87 var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
88 if (key !== 'Unidentified') {
89 return key;
90 }
91 }
92
93 // Browser does not implement `key`, polyfill as much of it as we can.
94 if (nativeEvent.type === 'keypress') {
95 var charCode = getEventCharCode(nativeEvent);
96
97 // The enter-key is technically both printable and non-printable and can
98 // thus be captured by `keypress`, no other non-printable key should.
99 return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
100 }
101 if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
102 // While user keyboard layout determines the actual meaning of each
103 // `keyCode` value, almost all function keys have a universal value.
104 return translateToKey[nativeEvent.keyCode] || 'Unidentified';
105 }
106 return '';
107}
108
109module.exports = getEventKey;
\No newline at end of file