69 lines
No EOL
1.9 KiB
TypeScript
69 lines
No EOL
1.9 KiB
TypeScript
import { ref, inject } from "vue";
|
|
import keyboardNameMap from "./keyBoardMaps/keyboardNameMap";
|
|
import keyboardCharMap from "./keyBoardMaps/keyboardCharMap";
|
|
// This catches keys from a physical keyboard, a soft keyboard on a tablet, or a
|
|
// scanner attached via USB
|
|
export default function useKeyDownHandler() {
|
|
interface KeyDownEvent {
|
|
keyCode: number;
|
|
shiftKey: boolean;
|
|
}
|
|
|
|
const emitter: any = inject("mitt");
|
|
const input = ref("");
|
|
|
|
// submits newSelfMessage event
|
|
function handleEnterKey() {
|
|
// does nothing if input value is empty
|
|
if (input.value === "") {
|
|
return;
|
|
}
|
|
const message = {
|
|
text: input.value,
|
|
audio: 0
|
|
};
|
|
// fire event with message payload
|
|
emitter.emit("newSelfMessage", message);
|
|
|
|
window.postMessage({
|
|
myTypeField: 'send-message',
|
|
message: message
|
|
}, '*')
|
|
}
|
|
|
|
function keyDownHandler(e: KeyDownEvent) {
|
|
// keyboardCharMap is an array of arrays, with each inner
|
|
// array having 2 columns - un-shifted, and shifted values.
|
|
// iCol = 0 is the un-shifted value, while iCol=1 is the shifted value.
|
|
// See the "keyboardCharMap", below, for printable characters.
|
|
// MODIFY keyboardCharMap to suit your needs if you want
|
|
// more/less/different characters to be considered "printable".
|
|
let iCol = 0;
|
|
if (e.shiftKey) {
|
|
iCol = 1;
|
|
}
|
|
const ch = keyboardCharMap[e.keyCode][iCol];
|
|
// Optionally do things with non-printables,
|
|
// like CR, ESC, Backspace, LF, Tab, Arrows, F1-F24, etc.
|
|
// See the arrary "keyboardNameMap", below, for possible keys.
|
|
const cmd = keyboardNameMap[e.keyCode];
|
|
switch (cmd) {
|
|
case "ENTER":
|
|
handleEnterKey();
|
|
break;
|
|
case "BACK_SPACE":
|
|
input.value = input.value.slice(0, -1);
|
|
break;
|
|
case "ESCAPE":
|
|
input.value = "";
|
|
break;
|
|
default:
|
|
input.value += ch;
|
|
}
|
|
}
|
|
|
|
return {
|
|
keyDownHandler,
|
|
input
|
|
};
|
|
} |