51 lines
1.5 KiB
TypeScript
51 lines
1.5 KiB
TypeScript
import { ref } from "vue";
|
|
import keyboardNameMap from "./keyBoardMaps/keyboardNameMap";
|
|
import keyboardCharMap from "./keyBoardMaps/keyboardCharMap";
|
|
|
|
interface KeyDownEvent {
|
|
keyCode: number;
|
|
shiftKey: boolean;
|
|
}
|
|
|
|
// This catches keys from a physical keyboard, a soft keyboard on a tablet, or a
|
|
// scanner attached via USB
|
|
export default function useKeyDownHandler(enterCallback: (input: string) => void | null) {
|
|
|
|
const input = ref("");
|
|
|
|
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":
|
|
enterCallback(input.value);
|
|
break;
|
|
case "BACK_SPACE":
|
|
input.value = input.value.slice(0, -1);
|
|
break;
|
|
case "ESCAPE":
|
|
input.value = "";
|
|
break;
|
|
default:
|
|
input.value += ch;
|
|
}
|
|
}
|
|
|
|
return {
|
|
keyDownHandler,
|
|
input
|
|
};
|
|
}
|