malwoden
Version:
   
313 lines • 13.7 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyboardContext = exports.KeyboardHandler = void 0;
/**
* Represents a global keyboard. Will likely only create one per app.
*
* You can bind/switch KeyboardContexts to the Keyboard handler
* to change input 'modes'.
*/
var KeyboardHandler = /** @class */ (function () {
/** Creates a new KeyboardHandler */
function KeyboardHandler(config) {
var _a;
this._isDown = new Set();
this._stopPropagation = (_a = config === null || config === void 0 ? void 0 : config.stopPropagation) !== null && _a !== void 0 ? _a : true;
document.addEventListener("keydown", this.onKeyDownEvent.bind(this));
document.addEventListener("keyup", this.onKeyUpEvent.bind(this));
}
KeyboardHandler.keyEventFromDomEvent = function (event, e) {
return {
key: e.keyCode,
repeat: e.repeat,
metaKey: e.metaKey,
shiftKey: e.shiftKey,
ctrlKey: e.ctrlKey,
event: event,
};
};
KeyboardHandler.prototype._checkPropagation = function (e) {
if (this._stopPropagation) {
e.stopPropagation();
return true;
}
return false;
};
KeyboardHandler.prototype.onKeyDownEvent = function (e) {
this._isDown.add(e.keyCode);
this._context &&
this._context.callOnDown(KeyboardHandler.keyEventFromDomEvent("keydown", e));
this._checkPropagation(e);
};
KeyboardHandler.prototype.onKeyUpEvent = function (e) {
this._isDown.delete(e.keyCode);
this._context &&
this._context.callOnUp(KeyboardHandler.keyEventFromDomEvent("keyup", e));
this._checkPropagation(e);
};
/**
* Sets the active context of the keyboard handler.
* @param context KeyboardContext - The context to use
*/
KeyboardHandler.prototype.setContext = function (context) {
this._context = context;
};
/**
* Clears the active context for the keyboard handler.
*/
KeyboardHandler.prototype.clearContext = function () {
var existing = this._context;
this._context = undefined;
return existing;
};
/**
* Returns if a key is currently held down.
* @param keyCode KeyCode | number - The keyCode to check
*/
KeyboardHandler.prototype.isKeyDown = function (keyCode) {
return this._isDown.has(keyCode);
};
/**
* Returns a promise that will resolve the next time a given keyCode is released.
* If no keyCode is given, it will return the next keyCode released.
* @param keyCode - The keyCode to listen to. If not provided, will monitor for any keycode.
* @returns - The pressed keyCode.
*/
KeyboardHandler.prototype.waitForKeyUp = function (keyCode) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve) {
var listener = function (e) {
if (keyCode === undefined || keyCode === e.keyCode) {
document.removeEventListener("keyup", listener);
resolve(e.keyCode);
}
};
document.addEventListener("keyup", listener);
})];
});
});
};
/**
* Returns a promise that will resolve the next time a given keyCode is pressed down. If
* no keyCode is given, it will return the next keyCode pressed.
* @param keyCode
* @returns - The pressed keyCode.
*/
KeyboardHandler.prototype.waitForKeyDown = function (keyCode) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve) {
var listener = function (e) {
if (keyCode === undefined || keyCode === e.keyCode) {
document.removeEventListener("keydown", listener);
resolve(e.keyCode);
}
};
document.addEventListener("keydown", listener);
})];
});
});
};
return KeyboardHandler;
}());
exports.KeyboardHandler = KeyboardHandler;
/**
* KeyboardContext represents a single 'mode' of the game's keyboard controls.
* For instance, you might have one context to use for the overworld, another for
* menus, another for inventory, etc.
*
* You can set the active context through a KeyboardHandler's setContext(ctx)
* and clearContext() methods.
*
* Normally the onDown/onUp callbacks can be used to listen for specific keys,
* but for more control onAnyDown/onAnyUp can be used to register callbacks
* that fire on any key press. These 'any' callbacks will always be the first
* to be called during a new key press.
*
* You can register multiple 'any' callbacks or key-specific callbacks for rare
* patterns,for instance registering 2 callbacks to fire when the 'E' key is
* pressed, etc.
*/
var KeyboardContext = /** @class */ (function () {
function KeyboardContext() {
this._onDown = new Map();
this._onUp = new Map();
this._anyKey = "any";
}
KeyboardContext.prototype._getOnDownFns = function (key) {
var _a;
return (_a = this._onDown.get(key)) !== null && _a !== void 0 ? _a : [];
};
KeyboardContext.prototype._getOnUpFns = function (key) {
var _a;
return (_a = this._onUp.get(key)) !== null && _a !== void 0 ? _a : [];
};
KeyboardContext.prototype._addOnDown = function (key, callback) {
var existing = this._getOnDownFns(key);
existing.push(callback);
this._onDown.set(key, existing);
};
KeyboardContext.prototype._addOnUp = function (key, callback) {
var existing = this._getOnUpFns(key);
existing.push(callback);
this._onUp.set(key, existing);
};
/**
* Fires callback on a specific key down. Can call multiple times to register multiple callbacks.
* @param key KeyCode | number - The Key to monitor
* @param callback (KeyHandlerEvent) => void - The callback
* @returns - The KeyboardContext
*/
KeyboardContext.prototype.onDown = function (key, callback) {
this._addOnDown(key, callback);
return this;
};
/**
* Clear an existing callback for a key. If no callback is provided, will clear
* all callbacks on that key.
* @param key KeyCode - The keycode to clear onDown.
* @param callback If no existing event is provided, will clear all
*/
KeyboardContext.prototype.clearOnDown = function (key, callback) {
var filtered = callback
? this._getOnDownFns(key).filter(function (f) { return f !== callback; })
: [];
this._onDown.set(key, filtered);
};
/**
* Fires callback on any key down. Can call multiple times to register multiple callbacks.
* @param callback (KeyHandlerEvent) => void - The callback
* @returns - The KeyboardContext
*/
KeyboardContext.prototype.onAnyDown = function (callback) {
this._addOnDown(this._anyKey, callback);
return this;
};
/**
* Clear a callback listening for any key. If no callback is provided, will clear
* all callbacks on listening for any keys.
* @param callback If no existing event is provided, will clear all
*/
KeyboardContext.prototype.clearOnAnyDown = function (callback) {
var filtered = callback
? this._getOnDownFns(this._anyKey).filter(function (f) { return f !== callback; })
: [];
this._onDown.set(this._anyKey, filtered);
};
/**
* Fires callback on a specific key up. Can call multiple times to register multiple callbacks.
* @param key KeyCode | number - The Key to monitor
* @param callback (KeyHandlerEvent) => void - The callback
* @returns - The KeyboardContext
*/
KeyboardContext.prototype.onUp = function (key, callback) {
this._addOnUp(key, callback);
return this;
};
/**
* Clear an existing callback for a key. If no callback is provided, will clear
* all callbacks on that key.
* @param key KeyCode - The keycode to clear onUp.
* @param callback If no existing event is provided, will clear all
*/
KeyboardContext.prototype.clearOnUp = function (key, callback) {
var filtered = callback
? this._getOnUpFns(key).filter(function (f) { return f !== callback; })
: [];
this._onUp.set(key, filtered);
};
/**
* Fires callback on any key up. Can call multiple times to register multiple callbacks.
* @param callback (KeyHandlerEvent) => void - The callback
* @returns - The KeyboardContext
*/
KeyboardContext.prototype.onAnyUp = function (callback) {
this._addOnUp(this._anyKey, callback);
return this;
};
/**
* Clear a callback listening for any key. If no callback is provided, will clear
* all callbacks on listening for any keys.
* @param callback If no existing event is provided, will clear all
*/
KeyboardContext.prototype.clearOnAnyUp = function (callback) {
var filtered = callback
? this._getOnUpFns(this._anyKey).filter(function (f) { return f !== callback; })
: [];
this._onUp.set(this._anyKey, filtered);
};
/**
* Programmatically call all callbacks as if a key was pressed.
* @param key KeyHandlerEvent
*/
KeyboardContext.prototype.callOnDown = function (event) {
var _a, _b;
var anyFns = (_a = this._onDown.get(this._anyKey)) !== null && _a !== void 0 ? _a : [];
var fns = (_b = this._onDown.get(event.key)) !== null && _b !== void 0 ? _b : [];
for (var _i = 0, anyFns_1 = anyFns; _i < anyFns_1.length; _i++) {
var f = anyFns_1[_i];
f(event);
}
for (var _c = 0, fns_1 = fns; _c < fns_1.length; _c++) {
var f = fns_1[_c];
f(event);
}
};
/**
* Programmatically call all callbacks as if a key was lifted.
* @param key KeyHandlerEvent
*/
KeyboardContext.prototype.callOnUp = function (event) {
var _a, _b;
var anyFns = (_a = this._onUp.get(this._anyKey)) !== null && _a !== void 0 ? _a : [];
var fns = (_b = this._onUp.get(event.key)) !== null && _b !== void 0 ? _b : [];
for (var _i = 0, anyFns_2 = anyFns; _i < anyFns_2.length; _i++) {
var f = anyFns_2[_i];
f(event);
}
for (var _c = 0, fns_2 = fns; _c < fns_2.length; _c++) {
var f = fns_2[_c];
f(event);
}
};
return KeyboardContext;
}());
exports.KeyboardContext = KeyboardContext;
//# sourceMappingURL=keyboard.js.map