-
Notifications
You must be signed in to change notification settings - Fork 11
/
Keyboard.js
98 lines (79 loc) · 1.89 KB
/
Keyboard.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* The MIT License (MIT)
* Copyright (c) 2017-present Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
*/
'use strict';
const BuiltInGate = require('../BuiltInGate');
const EventEmitter = require('events');
/**
* Main static emitter used for static methods on `Keyboard`.
*/
const keyboardEmitter = new EventEmitter();
/**
* A keyboard, implemented as a 16 bit register that stores
* the currently pressed key code.
*/
class Keyboard extends BuiltInGate {
constructor(options) {
super(options);
Keyboard.on('key', key => {
// Ctrl-c
if (key === '\u0003') {
this._listening = false;
process.exit();
}
this.getOutputPins()[0].setValue(key.charCodeAt(0));
});
}
/**
* Default blocking listener for CLI.
*
* Other clients should call `Keyboard.emit('key', key)`
* in their listeners.
*/
listen() {
if (this._listening) {
return;
}
const {stdin} = process;
stdin.setRawMode(true);
stdin.setEncoding('utf8');
stdin.on('data', key => Keyboard.emit('key', key));
stdin.resume();
this._listening = true;
return this;
}
/**
* Facade method for subscription.
*/
static emit(eventName, data) {
keyboardEmitter.emit(eventName, data);
return this;
}
/**
* Facade method for subscription.
*/
static on(eventName, listener) {
keyboardEmitter.on(eventName, listener);
return this;
}
/**
* Facade method for removing subscription.
*/
static removeListener(eventName, listener) {
keyboardEmitter.removeListener(eventName, listener);
return this;
}
}
/**
* Specification of the `Keyboard` gate.
*/
Keyboard.Spec = {
name: 'Keyboard',
description: `A keyboard, implemented as a 16 bit register that stores
the currently pressed key code.`,
inputPins: [],
outputPins: [{name: 'out', size: 16}],
truthTable: [],
};
module.exports = Keyboard;