Better typing

This commit is contained in:
dylan 2023-05-02 18:44:27 -07:00
parent 253b8e9567
commit 99a8c500c7
2 changed files with 55 additions and 9 deletions

View File

@ -1,4 +1,4 @@
const keyboard = new Map<string, {first: boolean, repeat: boolean, held: boolean}>();
const keyboard = new Map<number, {first: boolean, repeat: boolean, held: boolean}>();
export const K = {
ESCAPE: 256,
@ -31,10 +31,35 @@ export const K = {
ALT_RIGHT: 346,
}
export const shiftMap = {
"1": "!",
"2": "@",
"3": "#",
"4": "$",
"5": "%",
"6": "^",
"7": "&",
"8": "*",
"9": "(",
"0": ")",
"`": "~",
"-": "_",
"=": "+",
"[": "{",
"]": "}",
"\\": "|",
";": ":",
"'": '"',
",": "<",
".": ">",
"/": "?",
}
addEventListener("keydown", (evt) => {
console.log("keydown", evt.key, evt.key.charCodeAt(0));
const isRepeat = keyboard.has(evt.key) && keyboard.get(evt.key)?.held!;
keyboard.set(evt.key, {
const key = evt.key.charCodeAt(0);
const isRepeat = keyboard.has(key) && keyboard.get(key)?.held!;
keyboard.set(key, {
first: !isRepeat,
repeat: isRepeat,
held: true,
@ -43,7 +68,8 @@ addEventListener("keydown", (evt) => {
addEventListener("keyup", (evt) => {
console.log("keyup", evt.key, evt.key.charCodeAt(0));
keyboard.set(evt.key, {
const key = evt.key.charCodeAt(0);
keyboard.set(key, {
first: false,
repeat: false,
held: false,
@ -64,15 +90,28 @@ export const refreshKeyboard = () => {
})
}
export const keyPressed = (key: string) => {
export const keyPressed = (key: string | number) => {
if (typeof key === "string") {
key = key.charCodeAt(0);
}
return keyboard.has(key) && keyboard.get(key)?.repeat!;
}
export const keyDown = (key: string) => {
export const keyDown = (key: string | number) => {
if (typeof key === "string") {
key = key.charCodeAt(0);
}
return keyboard.has(key) && keyboard.get(key)?.held!;
}
export const keyReleased = (key: string) => {
export const shiftKeyDown = () => {
return keyDown(K.SHIFT_LEFT) || keyDown(K.SHIFT_RIGHT);
}
export const keyReleased = (key: string | number) => {
if (typeof key === "string") {
key = key.charCodeAt(0);
}
return keyboard.has(key) && !keyboard.get(key)?.held!;
}

11
repl.ts
View File

@ -1,12 +1,19 @@
import faux from "./builtins.ts";
import { getKeysPressed } from "./keyboard.ts";
import { getKeysPressed, shiftKeyDown, shiftMap } from "./keyboard.ts";
import { font } from "./font.ts";
let line = "";
const update = () => {
for (const key of getKeysPressed()) {
const char = key.toLowerCase();
let char = String.fromCharCode(key).toLowerCase();
if (shiftKeyDown()) {
if (char in shiftMap) {
char = shiftMap[char as keyof typeof shiftMap];
} else {
char = char.toUpperCase();
}
}
if (char in font) {
line += char;
}