diff --git a/src/lib/components/Keyboard.js b/src/lib/components/Keyboard.js index 1ba8e0d8..2c84f000 100644 --- a/src/lib/components/Keyboard.js +++ b/src/lib/components/Keyboard.js @@ -1,6 +1,7 @@ import './Keyboard.css'; // Services +import PhysicalKeyboard from '../services/PhysicalKeyboard'; import KeyboardLayout from '../services/KeyboardLayout'; import Utilities from '../services/Utilities'; @@ -42,6 +43,10 @@ class SimpleKeyboard { window['SimpleKeyboardInstances'][Utilities.camelCase(this.keyboardDOMClass)] = this; + /** + * Physical Keyboard support + */ + this.physicalKeyboardInterface = new PhysicalKeyboard(this); } handleButtonClicked = (button) => { diff --git a/src/lib/services/PhysicalKeyboard.js b/src/lib/services/PhysicalKeyboard.js new file mode 100644 index 00000000..db87dcba --- /dev/null +++ b/src/lib/services/PhysicalKeyboard.js @@ -0,0 +1,77 @@ +class PhysicalKeyboard { + constructor(simpleKeyboardInstance){ + this.simpleKeyboardInstance = simpleKeyboardInstance; + + if(!window['SimpleKeyboardPhysicalKeyboardInit']) + window['SimpleKeyboardPhysicalKeyboardInit'] = true; + else + return false; + + this.initKeyboardListener(); + } + + initKeyboardListener = () => { + // Normal Keyboard + document.addEventListener("keydown", (event) => { + if(this.simpleKeyboardInstance.options.physicalKeyboardHighlight){ + let buttonPressed = this.getSimpleKeyboardLayoutKey(event); + + this.simpleKeyboardInstance.dispatch(section => { + section.setOptions({ + buttonTheme: [ + { + class: "hg-selectedButton", + buttons: `${buttonPressed} {${buttonPressed}}` + } + ] + }) + }); + } + }); + + // Removing button style on keyup + document.addEventListener("keyup", (event) => { + if(this.simpleKeyboardInstance.options.physicalKeyboardHighlight){ + + this.simpleKeyboardInstance.dispatch(section => { + section.setOptions({ + buttonTheme: [] + }) + }); + } + }); + } + + getSimpleKeyboardLayoutKey = (event) => { + if(this.simpleKeyboardInstance.options.debug){ + console.log(event); + } + + let output; + + if( + event.code.includes("Numpad") || + event.code.includes("Shift") || + event.code.includes("Space") || + event.code.includes("Backspace") + ){ + output = event.code; + } else { + output = event.key; + } + + /** + * If button is not uppercase, casting to lowercase + */ + if ( + output !== output.toUpperCase() || + (event.code[0] === "F" && Number.isInteger(Number(event.code[1])) && event.code.length <= 3) + ) { + output = output.toLowerCase(); + } + + return output; + } +} + +export default PhysicalKeyboard; \ No newline at end of file