just-barcode-hook
Version:
A simple React hook for read barcode from devices emulating a fast keyboard.
70 lines (69 loc) • 2.18 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = useBarcodeScanner;
const react_1 = require("react");
/**
* Simple JavaScript utility to listen for barcode scanners emulating keyboard
*/
function useBarcodeScanner(options) {
let fun;
const optionsScanner = (0, react_1.useMemo)(() => {
if (typeof window === 'undefined' || typeof document === 'undefined')
return null;
return Object.assign({
latency: 50,
minLength: 3,
element: document,
endKeys: ['Enter'],
validKey: /^\w$/,
}, options);
}, [options]);
let prevTime = 0;
let code = '';
function EventHandler(e) {
const { key, timeStamp } = e;
const timeDiff = timeStamp - prevTime;
prevTime = timeStamp;
// Ignore shift key
if (key === 'Shift')
return;
const isValid = optionsScanner?.validKey?.test(key);
const isEndKey = optionsScanner?.endKeys?.includes(key);
if (optionsScanner?.latency && timeDiff > optionsScanner.latency) {
// Maybe a normal key press or start of barcode
if (!isEndKey && isValid) {
code = key;
return;
}
code = '';
return;
}
if (isValid) {
// Still scanning
code += key;
return;
}
if (isEndKey) {
// End of barcode
if (optionsScanner?.minLength &&
code.length >= optionsScanner.minLength) {
fun(code, e);
return;
}
}
// Invalid character, reset
code = '';
return;
}
return {
on: function (handler) {
optionsScanner?.element?.removeEventListener('keydown', EventHandler, true);
fun = handler;
code = '';
optionsScanner?.element?.addEventListener('keydown', EventHandler, true);
},
off: function () {
optionsScanner?.element?.removeEventListener('keydown', EventHandler, true);
},
};
}