93 lines
No EOL
3.2 KiB
JavaScript
93 lines
No EOL
3.2 KiB
JavaScript
const FILTER_START = 'Testing ... (interrupt to exit)';
|
|
|
|
const ACTION_KEYUP = { id: 0, action: 'keyup' };
|
|
const ACTION_KEYDOWN = { id: 1, action: 'keydown' };
|
|
const ACTION_KEYHOLD = { id: 2, action: 'keyhold' };
|
|
|
|
const VARIABLE_KEY = '{{ key }}';
|
|
const VARIABLE_TYPE = '{{ type }}';
|
|
|
|
class Keyfilter {
|
|
constructor(config) {
|
|
if (config == undefined || config.length == 0) {
|
|
return;
|
|
}
|
|
this.actions = new Map();
|
|
for (var index = 0; index < config.length; index++) {
|
|
var type = ACTION_KEYDOWN;
|
|
switch (config[index].type.toLowerCase()) {
|
|
case ACTION_KEYUP.action:
|
|
type = ACTION_KEYUP;
|
|
break;
|
|
case ACTION_KEYHOLD.action:
|
|
type = ACTION_KEYHOLD;
|
|
break;
|
|
}
|
|
var command = config[index].command;
|
|
var args = config[index].args;
|
|
var delay = config[index].delay;
|
|
this.actions.set(config[index].key.toUpperCase(), { type, command, args, delay });
|
|
}
|
|
}
|
|
filterActive(input) {
|
|
if (this.active) {
|
|
return true;
|
|
}
|
|
input = input.toString();
|
|
var index = input.indexOf(FILTER_START);
|
|
if (index == -1) {
|
|
return;
|
|
}
|
|
input = input.substring(index + FILTER_START.length).trim();
|
|
this.active = true;
|
|
return true;
|
|
}
|
|
filter(input) {
|
|
if (input == undefined || input.length == 0) {
|
|
return;
|
|
}
|
|
input = input.toString();
|
|
if (!this.filterActive(input)) {
|
|
return;
|
|
}
|
|
var lines = input.split("\n");
|
|
for (var index = 0; index < lines.length; index++) {
|
|
var line = lines[index];
|
|
if (line.length == 0) {
|
|
continue;
|
|
}
|
|
for (var [key, value] of this.actions) {
|
|
if (!line.includes(key)) {
|
|
continue;
|
|
}
|
|
if (!line.endsWith('value ' + value.type.id)) {
|
|
continue;
|
|
}
|
|
var action = this.actions.get(key);
|
|
if (this.shouldBeDelayed(action)) {
|
|
return { key: key, type: action.type.action, delayed: true };
|
|
}
|
|
action.captured = new Date().getTime();
|
|
return this.replaceVariables({ key: key, type: action.type.action, command: action.command, args: action.args });
|
|
}
|
|
}
|
|
}
|
|
replaceVariables(filtered) {
|
|
for (var index = 0; index < filtered.args.length; index++) {
|
|
filtered.args[index] = filtered.args[index].replace(VARIABLE_KEY, filtered.key);
|
|
filtered.args[index] = filtered.args[index].replace(VARIABLE_TYPE, filtered.type);
|
|
}
|
|
return filtered;
|
|
}
|
|
shouldBeDelayed(action) {
|
|
if (action.delay == undefined || action.delay == 0 || action.captured == undefined) {
|
|
return false;
|
|
}
|
|
return new Date().getTime() - action.captured < action.delay;
|
|
}
|
|
isValid() {
|
|
return this.actions != undefined && this.actions.size > 0;
|
|
}
|
|
}
|
|
|
|
module.exports = Keyfilter; |