-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkbd_processor.js
73 lines (72 loc) · 2.27 KB
/
kbd_processor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
function kbd_processor(commands, progressMsgFunc, actionMsgFunc) {
var numericPrefixString = "";
var currentString = "";
var root = { 'char' : 'root' };
var currentNode = root;
function progressMsg() {
if (progressMsgFunc) {
progressMsgFunc(numericPrefixString + currentString);
}
}
function actionMsg(n) {
if (actionMsgFunc) {
actionMsgFunc(numericPrefixString + currentString
+ (currentNode.msgfunc ? (": " + currentNode.msgfunc(n)) : ""));
}
}
var kp = {
addCommand: function(cmd) {
var cs = cmd.seq.split('');
var node = root;
cs.forEach(function(c) {
if (!(c in node)) {
node[c] = { 'char': c };
}
node = node[c];
});
node.action = cmd.action;
node.msgfunc = cmd.msgfunc;
},
key: function(c) {
if (currentNode == root && c >= '0' && c <= '9') {
numericPrefixString += c;
progressMsg();
return;
}
if (c in currentNode) {
currentNode = currentNode[c];
currentString += c;
progressMsg();
if (currentNode.action) {
if (numericPrefixString !== "") {
var n = parseInt(numericPrefixString,10);
currentNode.action(n);
actionMsg(n);
} else {
currentNode.action();
actionMsg();
}
numericPrefixString = "";
currentNode = root;
currentString = "";
return;
}
} else {
progressMsg();
if (currentNode !== root) {
numericPrefixString = "";
currentNode = root;
currentString = "";
this.key(c);
}
}
}
};
commands.forEach(function(cmd) {
if ("seq" in cmd) {
kp.addCommand(cmd);
}
});
return kp;
}
module.exports = kbd_processor;