69 lines
2 KiB
TypeScript
69 lines
2 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 = {
|
|
content: input.value,
|
|
signature: "EnriqueH",
|
|
outgoing: true,
|
|
modifier: "sf",
|
|
imgURL: "/test/path",
|
|
id: null
|
|
};
|
|
// fire event with message payload
|
|
emitter.emit("newSelfMessage", 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;
|
|
}
|
|
console.log(e.shiftKey);
|
|
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
|
|
};
|
|
}
|