ninwa/libs/keyfilter.js

94 lines
3.2 KiB
JavaScript
Raw Normal View History

2022-02-15 04:33:19 +01:00
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 }}';
2022-02-15 04:33:19 +01:00
class Keyfilter {
constructor(config) {
if (config == undefined || config.length == 0) {
return;
}
this.actions = new Map();
for (var index = 0; index < config.length; index++) {
var grep = config[index].grep;
2022-02-15 04:33:19 +01:00
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(), { grep, type, command, args, delay });
2022-02-15 04:33:19 +01:00
}
}
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 });
2022-02-15 04:33:19 +01:00
}
}
}
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;
}
2022-02-15 04:33:19 +01:00
shouldBeDelayed(action) {
if (action.delay == undefined || action.delay == 0 || action.captured == undefined) {
2022-02-15 04:33:19 +01:00
return false;
}
return new Date().getTime() - action.captured < action.delay;
2022-02-15 04:33:19 +01:00
}
isValid() {
return this.actions != undefined && this.actions.size > 0;
}
2022-02-15 04:33:19 +01:00
}
module.exports = Keyfilter;