Add 'KeyboardEvent.key' and 'KeyboardEvent.code' polyfills

This commit is contained in:
Dmitry Lyzo
2026-05-13 22:40:03 +03:00
parent 62632da745
commit 08c0f8f3f8
2 changed files with 67 additions and 28 deletions
+67
View File
@@ -1,6 +1,8 @@
/**
* Polyfill for KeyboardEvent
* - Constructor.
* - 'code' property.
* - 'key' property.
*/
(function (window) {
@@ -42,4 +44,69 @@
KeyboardEvent.prototype = KeyboardEventOriginal.prototype;
window.KeyboardEvent = KeyboardEvent;
}
if (!('code' in KeyboardEvent.prototype)) {
/**
* Key code mapping.
*/
const KeyCodes = {
13: 'Enter',
19: 'Pause',
27: 'Escape',
32: 'Space',
37: 'ArrowLeft',
38: 'ArrowUp',
39: 'ArrowRight',
40: 'ArrowDown'
};
// Add [a..z]
for (let i = 65; i <= 90; i++) {
KeyCodes[i] = `Key${String.fromCharCode(i)}`;
}
// Add [0..9]
for (let i = 48; i <= 57; i++) {
KeyCodes[i] = `Digit${String.fromCharCode(i)}`;
}
Object.defineProperty(KeyboardEvent.prototype, 'code', {
get: function () {
return KeyCodes[this.keyCode] || '';
},
enumerable: true,
configurable: true
});
}
if (!('key' in KeyboardEvent.prototype)) {
/**
* Key mapping.
*/
const Keys = {
13: 'Enter',
19: 'Pause',
27: 'Escape',
32: 'Space',
37: 'ArrowLeft',
38: 'ArrowUp',
39: 'ArrowRight',
40: 'ArrowDown'
};
// Add [a..z]
for (let i = 65; i <= 90; i++) {
const c = String.fromCharCode(i);
Keys[i] = [c.toLowerCase(), c.toUpperCase()];
}
Object.defineProperty(KeyboardEvent.prototype, 'key', {
get: function () {
const key = Keys[this.keyCode] || '';
return Array.isArray(key) ? key[+this.shiftKey] : key;
},
enumerable: true,
configurable: true
});
}
}(window));
-28
View File
@@ -12,15 +12,6 @@ import appSettings from './settings/appSettings';
* Key name mapping.
*/
const KeyNames = {
13: 'Enter',
19: 'Pause',
27: 'Escape',
32: 'Space',
37: 'ArrowLeft',
38: 'ArrowUp',
39: 'ArrowRight',
40: 'ArrowDown',
// UWP WebView section start --
// Navigation Up/Down/Left/Right is part of TVJS directionalnavigation-1.0.0.0.js
// Unsure what this is used for. Media remote?
@@ -102,25 +93,6 @@ const InteractiveElements = ['INPUT', 'TEXTAREA'];
*/
const NonInteractiveInputElements = ['button', 'checkbox', 'color', 'file', 'hidden', 'image', 'radio', 'reset', 'submit'];
let hasFieldCode = false;
try {
hasFieldCode = 'code' in new KeyboardEvent('keydown');
} catch (e) {
console.error("error checking 'code' field", e);
}
if (!hasFieldCode) {
// Add [a..z]
for (let i = 65; i <= 90; i++) {
KeyNames[i] = `Key${String.fromCharCode(i)}`;
}
// Add [0..9]
for (let i = 48; i <= 57; i++) {
KeyNames[i] = `Digit${String.fromCharCode(i)}`;
}
}
/**
* Returns key name from event.
*