-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathScanner.js
More file actions
executable file
·98 lines (77 loc) · 2.07 KB
/
Copy pathScanner.js
File metadata and controls
executable file
·98 lines (77 loc) · 2.07 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import ScanListener from './ScanListener.js';
import ScanType from './ScanType.js';
export default class Scanner {
static ignoreSelector = 'input, js-disable-barcode-scan';
static ignoreKeys = ['Shift', 'Unidentified'];
static finishKey = 'Enter';
static triple(callback, type = ScanType.any()) {
return new Scanner(ScanListener.triple(type, callback)).listen();
}
static single(callback, type = ScanType.any()) {
return new Scanner(ScanListener.single(type, callback)).listen();
}
constructor(listener) {
this.input = '';
this.enabled = true;
this.listeners = listener ? [listener] : [];
this.emptyScanListeners = [];
}
addListener(listener) {
this.listeners.push(listener);
return this;
}
onEmptyScan(callback) {
this.emptyScanListeners.push(callback);
return this;
}
listen(context = document.body) {
context.addEventListener('keypress', this.handleKeyUp.bind(this));
return this;
}
blurButtonIfFocused() {
/BUTTON|A/i.test(document.activeElement.tagName) && document.activeElement.blur();
return this;
}
handleKeyUp({ key, target }) {
if (!this.enabled || Scanner.ignoreKeys.includes(key)) {
return;
}
this.blurButtonIfFocused();
// Don't add to scanner input if we're typing into an ignored field (like an input)
if (target.matches(Scanner.ignoreSelector) || target.closest(Scanner.ignoreSelector)) {
this.input = '';
return;
}
// add the key to the scanner input to build the barcode
if (key !== Scanner.finishKey) {
this.input += key;
return;
}
// don't do anything if the scanner input is empty
if (this.input === '') {
this.handleEmptyScan();
return;
}
this.handleScan();
// reset the scanner input, ready for next time
this.input = '';
}
handleEmptyScan() {
this.emptyScanListeners.forEach(callback => callback());
}
handleScan() {
const entry = {
rawBarcode: this.input,
scannedAt: new Date(),
}
this.listeners.forEach(listener => listener.handleScan(entry));
}
enable() {
this.enabled = true;
return this;
}
disable() {
this.enabled = false;
return this;
}
}