|
| 1 | +/** |
| 2 | + * Copyright (c) Jesse Koerhuis 2024. |
| 3 | + * |
| 4 | + * This code was written by Jesse Koerhuis. For more information, please refer to the LICENSE file distributed with this |
| 5 | + * software. For more content, visit https://jessekoerhuis.nl/. |
| 6 | + */ |
| 7 | + |
| 8 | +import { onBeforeUnmount, ref } from 'vue'; |
| 9 | + |
| 10 | +const keyboard = { |
| 11 | + event: 'keydown', |
| 12 | + key: { |
| 13 | + enter: 'Enter', |
| 14 | + shift: 'Shift', |
| 15 | + }, |
| 16 | +}; |
| 17 | + |
| 18 | +const scannerConfig = { |
| 19 | + timeout: 100, |
| 20 | +}; |
| 21 | + |
| 22 | +export default function useBarcodeScanner() { |
| 23 | + const barcode = ref (''); |
| 24 | + const barcodeScannerInterval = ref(); |
| 25 | + const listeningActive = ref(false); |
| 26 | + const onScanCallback = ref(); |
| 27 | + |
| 28 | + function _createScannedBarcodeData(barcodeValue) { |
| 29 | + const date = new Date(); |
| 30 | + |
| 31 | + return { |
| 32 | + timestamp: date.getTime(), |
| 33 | + value: barcodeValue, |
| 34 | + }; |
| 35 | + } |
| 36 | + |
| 37 | + function _registerScannerInput(event) { |
| 38 | + if (barcodeScannerInterval.value) { |
| 39 | + clearInterval(barcodeScannerInterval.value); |
| 40 | + } |
| 41 | + |
| 42 | + if (event instanceof KeyboardEvent && event.code === keyboard.key.enter) { |
| 43 | + if (barcode.value && onScanCallback.value) { |
| 44 | + onScanCallback.value( |
| 45 | + _createScannedBarcodeData(barcode.value), |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + barcode.value = ''; |
| 50 | + |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + if (event instanceof KeyboardEvent && event.code !== keyboard.key.shift) { |
| 55 | + barcode.value += event.key; |
| 56 | + } |
| 57 | + |
| 58 | + barcodeScannerInterval.value = setInterval(() => { |
| 59 | + barcode.value = ''; |
| 60 | + }, scannerConfig.timeout); |
| 61 | + } |
| 62 | + |
| 63 | + function stopListening() { |
| 64 | + listeningActive.value = false; |
| 65 | + |
| 66 | + document.removeEventListener(keyboard.event, _registerScannerInput); |
| 67 | + |
| 68 | + if (barcodeScannerInterval.value) { |
| 69 | + clearInterval(barcodeScannerInterval.value); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + function listen(callback) { |
| 74 | + if (listeningActive.value) { |
| 75 | + stopListening(); |
| 76 | + } |
| 77 | + |
| 78 | + listeningActive.value = true; |
| 79 | + onScanCallback.value = callback; |
| 80 | + |
| 81 | + document.addEventListener(keyboard.event, _registerScannerInput); |
| 82 | + } |
| 83 | + |
| 84 | + onBeforeUnmount(() => { |
| 85 | + stopListening(); |
| 86 | + }); |
| 87 | + |
| 88 | + return { barcode, listen, stopListening }; |
| 89 | +} |
0 commit comments