avocado-old/packages/input/action-registry.js
2019-10-11 02:17:00 -05:00

95 lines
2.0 KiB
JavaScript

import * as I from 'immutable';
import {compose, EventEmitter} from '@avocado/core';
const decorate = compose(
EventEmitter,
);
export class ActionRegistry extends decorate(class {}) {
constructor() {
super();
this.actionKeys = new Map();
this.keyActions = {};
this.normalizer = undefined;
this._actionIds = {};
this._stream = [];
this._actionTransformers = {};
}
actionForKey(key) {
return this.keyActions[key];
}
drain() {
const stream = this._stream;
this._stream = [];
return stream;
}
listen(normalizer) {
// Only listen once.
if (this.normalizer) {
return;
}
this.normalizer = normalizer;
this.normalizer.on('keyUp', this.onKeyUp, this);
this.normalizer.on('keyDown', this.onKeyDown, this);
}
keyForAction(action) {
return this.actionKeys[action];
}
mapKeysToActions(map) {
for (const action in map) {
const key = map[action];
this.keyActions[key] = action;
this.actionKeys[action] = key;
}
}
onKeyDown(key) {
if (this.keyActions[key]) {
const action = this.keyActions[key];
let value;
if (this._actionTransformers[action]) {
value = this._actionTransformers[action]('keyDown');
}
else {
value = 1;
}
this._stream.push({action, value});
}
}
onKeyUp(key) {
if (this.keyActions[key]) {
const action = this.keyActions[key];
let value;
if (this._actionTransformers[action]) {
value = this._actionTransformers[action]('keyUp');
}
else {
value = 0;
}
this._stream.push({action, value});
}
}
setActionTransformerFor(action, transformer) {
this._actionTransformers[action] = transformer;
}
stopListening(normalizer) {
if (!this.normalizer) {
return;
}
this.normalizer.off('keyUp', this.onKeyUp);
this.normalizer.off('keyDown', this.onKeyDown);
this.normalizer = undefined;
}
}