Skip to content

Commit 81a2934

Browse files
committed
Return a stream of all keypresses if no key is specified, closes #2
1 parent f38d717 commit 81a2934

File tree

3 files changed

+30
-5
lines changed

3 files changed

+30
-5
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,10 @@ const drivers = {
3535
function main({Keys}) { // Your amazing main function }
3636
```
3737
38-
- Call `Keys.presses` with the name of the key for which you'd like a stream of presses. Currently, Cycle Keys supports inputting keys as strings only
38+
- Call `Keys.presses` without any arguments to get a stream of all keypresses. You can also call `presses` with the name of a key to only get keypresses for that key. Currently, Cycle Keys supports inputting keys as strings only
3939
4040
```js```
41+
const allKeypresses$ = Keys.presses();
4142
const esc$ = Keys.presses('esc');
4243
const shift$ = Keys.presses('shift');
4344
```

src/keys-driver.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,15 @@ export function makeKeysDriver () {
55
return function keysDriver() {
66
return {
77
presses (key) {
8-
const code = keycode(key);
8+
let keypress$ = Observable.fromEvent(document.body, 'keypress');
99

10-
return Observable
11-
.fromEvent(document.body, 'keypress')
12-
.filter(ev => ev.keyCode === code);
10+
if (key) {
11+
const code = keycode(key);
12+
13+
keypress$ = keypress$.filter(event => event.keyCode === code);
14+
}
15+
16+
return keypress$;
1317
}
1418
}
1519
}

test/keys-test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,26 @@ import simulant from 'simulant';
55

66
describe("makeKeysDriver", () => {
77
describe("presses", () => {
8+
it("returns a stream of all keypresses", () => {
9+
const sources = makeKeysDriver()();
10+
11+
const keyCodes = [74, 75, 76];
12+
let keypressEvents;
13+
14+
sources.presses().take(3).toArray().subscribe((events) => {
15+
keypressEvents = events.map(event => event.keyCode);
16+
});
17+
18+
19+
keyCodes.forEach(function (keyCode) {
20+
const event = simulant('keypress', {keyCode});
21+
22+
simulant.fire(document.body, event);
23+
});
24+
25+
assert.deepEqual(keypressEvents, keyCodes, 'keycodes match given keys');
26+
});
27+
828
it("returns a stream of keypress events for the given key", (done) => {
929
const sources = makeKeysDriver()();
1030

0 commit comments

Comments
 (0)