avocado-old/packages/input/action-registry.js

95 lines
2.0 KiB
JavaScript
Raw Normal View History

import * as I from 'immutable';
2019-04-28 23:45:03 -05:00
import {compose, EventEmitter} from '@avocado/core';
const decorate = compose(
EventEmitter,
);
export class ActionRegistry extends decorate(class {}) {
constructor() {
super();
2019-10-11 02:17:00 -05:00
this.actionKeys = new Map();
this.keyActions = {};
this.normalizer = undefined;
2019-10-11 02:17:00 -05:00
this._actionIds = {};
this._stream = [];
this._actionTransformers = {};
}
actionForKey(key) {
2019-10-11 02:17:00 -05:00
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) {
2019-10-11 02:17:00 -05:00
return this.actionKeys[action];
}
mapKeysToActions(map) {
2019-10-11 02:17:00 -05:00
for (const action in map) {
const key = map[action];
this.keyActions[key] = action;
this.actionKeys[action] = key;
}
}
onKeyDown(key) {
2019-10-11 02:17:00 -05:00
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) {
2019-10-11 02:17:00 -05:00
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});
}
}
2019-10-11 02:17:00 -05:00
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;
}
}