capybara/frontend/src/Keyboard.js

83 lines
2.5 KiB
JavaScript
Raw Normal View History

import SimpleKeyboard from "simple-keyboard";
class KeyboardController {
constructor(connection) {
this.connection = connection;
this.keyboard = null;
}
_sendLetterPress(l) {
this.connection.sendMessage("k", [l]);
}
_sendLetterRelease(l) {
this.connection.sendMessage("k", [l]);
}
bindTo(element) {
this.keyboard = new SimpleKeyboard(element, {
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"
}
});
}
onKeyPress(button) {
if (button === "{shift}" || button === "{lock}")
return this.handleShift();
if (button === "{numbers}" || button === "{abc}")
return this.handleNumbers();
this._sendLetterPress(button);
}
onKeyReleased(button) {
this._sendLetterRelease(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;