Skip to content

Commit 9a1c593

Browse files
Merge pull request #17 from roman-yagodin/master
#1 Use onData for keyboard input
2 parents a128b1d + f50e58d commit 9a1c593

File tree

1 file changed

+18
-26
lines changed

1 file changed

+18
-26
lines changed

Diff for: js/app.js

+18-26
Original file line numberDiff line numberDiff line change
@@ -237,8 +237,8 @@ async function menu(options, showOptions = true) {
237237
}
238238

239239
while (true) {
240-
const evt = await readKey("??", true);
241-
const numKey = evt.keyCode - 48;
240+
const key = await readKey("??", true);
241+
const numKey = parseInt(key);
242242
if (numKey !== NaN && numKey >= 0 && numKey < options.length) {
243243
return options[numKey].choice;
244244
}
@@ -253,22 +253,22 @@ async function waitKey() {
253253
const interval = setInterval(() => {
254254
const key = game.lastKey;
255255
if (key) {
256-
if (key.key !== "Unidentified" // Chrome and alike on Android (not working)
257-
&& key.key !== "Shift" && key.key !== "Control" && key.key !== "Alt" && key.key !== "Meta") {
258-
clearInterval(interval);
259-
console.log({key: game.lastKey});
260-
resolve(game.lastKey);
261-
}
256+
clearInterval(interval);
257+
console.log({key: game.lastKey});
258+
resolve(game.lastKey);
262259
}
263260
}, 100)
264261
});
265262
}
266263

267-
function getKeyString(evt) {
268-
if (evt) {
269-
if (evt.keyCode >= 48 && evt.keyCode <= 48 + 9) {
270-
return (evt.keyCode - 48).toString();
271-
}
264+
function getKeyString(key) {
265+
if (key) {
266+
if (key === "\r") {
267+
return "Enter";
268+
}
269+
else if (/^[0-9]$/.test(key)) {
270+
return key;
271+
}
272272
}
273273
return "Anykey";
274274
}
@@ -283,18 +283,18 @@ async function readKey(prompt = "..", echo = false) {
283283
resetStyle();
284284

285285
// TODO: Add option to don't await input indefinitely - e.g. set timer and "run" CLS command from time to time.
286-
const evt = await waitKey();
286+
const key = await waitKey();
287287

288288
if (echo) {
289289
setStyle(styles.bold + styles.white);
290-
await typeln("\b".repeat(prompt.length) + "<< " + getKeyString(evt));
290+
await typeln("\b".repeat(prompt.length) + "<< " + getKeyString(key));
291291
resetStyle();
292292
}
293293
else {
294294
await type("\b".repeat(prompt.length));
295295
}
296296

297-
return evt;
297+
return key;
298298
}
299299
}
300300

@@ -821,17 +821,9 @@ export class App {
821821
t.open(document.getElementById('terminal'));
822822
fitAddon.fit();
823823

824-
t.onKey(e => {
825-
window.game.lastKey = e.domEvent;
826-
});
827-
828-
/*
829-
t.attachCustomKeyEventHandler(evt => {
830-
if (evt.type === "keyup") {
831-
window.game.lastKey = evt;
832-
}
824+
t.onData(e => {
825+
window.game.lastKey = e;
833826
});
834-
*/
835827

836828
window.addEventListener("resize", evt => {
837829
fitAddon.fit();

0 commit comments

Comments
 (0)