import SimpleKeyboard from "simple-keyboard"; class KeyboardController { constructor(connection) { this.connection = connection; this.keyboard = null; this.keyboardDiv = null; } _sendKeyPress(l) { this.connection.sendMessage("k", [l]); } mountOn(element) { if (this.keyboardDiv) return; // Already mounted; this.keyboardDiv = document.createElement("div"); this.keyboardDiv.classList.add("keyboard"); element.appendChild(this.keyboardDiv); this.keyboard = new SimpleKeyboard(this.keyboardDiv, { onKeyPress: this.onKeyPress.bind(this), mergeDisplay: true, layoutName: "default", // refer to: https://hodgef.com/simple-keyboard/demos/?d=mobile layout: { default: [ "q w e r t y u i o p", "a s d f g h j k l", "{shift} z x c v b n m {backspace}", "{numbers} {space} {ent}" ], shift: [ "Q W E R T Y U I O P", "A S D F G H J K L", "{shift} Z X C V B N M {backspace}", "{numbers} {space} {ent}" ], numbers: ["1 2 3", "4 5 6", "7 8 9", "{abc} 0 {backspace}"] }, display: { "{numbers}": "123", "{ent}": "return", "{escape}": "esc ⎋", "{tab}": "tab ⇥", "{backspace}": "⌫", "{capslock}": "caps lock ⇪", "{shift}": "⇧", "{controlleft}": "ctrl ⌃", "{controlright}": "ctrl ⌃", "{altleft}": "alt ⌥", "{altright}": "alt ⌥", "{metaleft}": "cmd ⌘", "{metaright}": "cmd ⌘", "{abc}": "ABC" } }); } unmount() { if (!this.keyboardDiv) return; // Not mounted - don't do anything this.keyboardDiv.parentElement.removeChild(this.keyboardDiv); this.keyboardDiv = null; } onKeyPress(button) { if (button === "{shift}" || button === "{lock}") return this.handleShift(); if (button === "{numbers}" || button === "{abc}") return this.handleNumbers(); this._sendKeyPress(button); } handleShift() { this.keyboard.setOptions({ layoutName: this.keyboard.options.layoutName === "default" ? "shift" : "default" }); } handleNumbers() { this.keyboard.setOptions({ layoutName: this.keyboard.options.layoutName !== "numbers" ? "numbers" : "default" }); } } export default KeyboardController;