80 lines
1.6 KiB
JavaScript
80 lines
1.6 KiB
JavaScript
|
import * as I from 'immutable';
|
||
|
|
||
|
import {compose} from '@avocado/core';
|
||
|
import {EventEmitter} from '@avocado/mixins';
|
||
|
|
||
|
const decorate = compose(
|
||
|
EventEmitter,
|
||
|
);
|
||
|
|
||
|
export class ActionRegistry extends decorate(class {}) {
|
||
|
|
||
|
constructor() {
|
||
|
super();
|
||
|
this.mapActionToKey = new Map();
|
||
|
this.mapKeyToAction = {};
|
||
|
this.normalizer = undefined;
|
||
|
this._state = I.Map();
|
||
|
}
|
||
|
|
||
|
actionForKey(key) {
|
||
|
return this.mapKeyToAction[key];
|
||
|
}
|
||
|
|
||
|
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.mapActionToKey.get(action);
|
||
|
}
|
||
|
|
||
|
mapKeysToActions(map) {
|
||
|
for (const key in map) {
|
||
|
const action = map[key];
|
||
|
this.mapKeyToAction[key] = action;
|
||
|
this.mapActionToKey.set(action, key);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
onKeyDown(key) {
|
||
|
if (this.mapKeyToAction[key]) {
|
||
|
const action = this.mapKeyToAction[key];
|
||
|
this._state = this._state.set(action, true);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
onKeyUp(key) {
|
||
|
if (this.mapKeyToAction[key]) {
|
||
|
const action = this.mapKeyToAction[key];
|
||
|
this._state = this._state.delete(action);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
get state() {
|
||
|
return this._state;
|
||
|
}
|
||
|
|
||
|
set state(state) {
|
||
|
this._state = state;
|
||
|
}
|
||
|
|
||
|
stopListening(normalizer) {
|
||
|
if (!this.normalizer) {
|
||
|
return;
|
||
|
}
|
||
|
this.normalizer.off('keyUp', this.onKeyUp);
|
||
|
this.normalizer.off('keyDown', this.onKeyDown);
|
||
|
this.normalizer = undefined;
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
export {InputPacket} from './packet/input.packet';
|