use-scan-detection
Version:
A react hook for detecting barcode scanner input.
82 lines • 3.4 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
/**
* Checks for scan input within a container and sends the output to a callback function.
* @param param0 Config object
*/
var useScanDetection = function (_a) {
var _b = _a.timeToEvaluate, timeToEvaluate = _b === void 0 ? 100 : _b, _c = _a.averageWaitTime, averageWaitTime = _c === void 0 ? 50 : _c, _d = _a.startCharacter, startCharacter = _d === void 0 ? [] : _d, _e = _a.endCharacter, endCharacter = _e === void 0 ? [13, 27] : _e, onComplete = _a.onComplete, onError = _a.onError, _f = _a.minLength, minLength = _f === void 0 ? 1 : _f, ignoreIfFocusOn = _a.ignoreIfFocusOn, _g = _a.stopPropagation, stopPropagation = _g === void 0 ? false : _g, _h = _a.preventDefault, preventDefault = _h === void 0 ? false : _h, _j = _a.container, container = _j === void 0 ? document : _j;
var buffer = react_1.useRef([]);
var timeout = react_1.useRef(false);
var clearBuffer = function () {
buffer.current = [];
};
var evaluateBuffer = function () {
clearTimeout(timeout.current);
var sum = buffer.current
.map(function (_a, k, arr) {
var time = _a.time;
return k > 0 ? time - arr[k - 1].time : 0;
})
.slice(1)
.reduce(function (total, delta) { return total + delta; }, 0);
var avg = sum / (buffer.current.length - 1);
var code = buffer.current
.slice(startCharacter.length > 0 ? 1 : 0)
.map(function (_a) {
var char = _a.char;
return char;
})
.join("");
if (avg <= averageWaitTime
&& buffer.current.slice(startCharacter.length > 0 ? 1 : 0).length >= minLength) {
onComplete(code);
}
else {
avg <= averageWaitTime && !!onError && onError(code);
}
clearBuffer();
};
var onKeyDown = react_1.useCallback(function (event) {
if (event.currentTarget !== ignoreIfFocusOn) {
if (endCharacter.includes(event.keyCode)) {
evaluateBuffer();
}
if (buffer.current.length > 0 || startCharacter.includes(event.keyCode) || startCharacter.length === 0) {
clearTimeout(timeout.current);
timeout.current = setTimeout(evaluateBuffer, timeToEvaluate);
buffer.current.push({ time: performance.now(), char: event.key });
}
}
if (stopPropagation) {
event.stopPropagation();
}
if (preventDefault) {
event.preventDefault();
}
}, [
startCharacter,
endCharacter,
timeToEvaluate,
onComplete,
onError,
minLength,
ignoreIfFocusOn,
stopPropagation,
preventDefault
]);
react_1.useEffect(function () {
return function () {
clearTimeout(timeout.current);
};
}, []);
react_1.useEffect(function () {
container.addEventListener("keydown", (onKeyDown));
return function () {
container.removeEventListener("keydown", (onKeyDown));
};
}, [onKeyDown]);
};
exports.default = useScanDetection;
//# sourceMappingURL=index.js.map
;