2
0
mirror of https://github.com/frappe/books.git synced 2024-11-08 14:50:56 +00:00

incr: add keydown listener for scanner

This commit is contained in:
18alantom 2023-01-18 12:53:15 +05:30
parent b9c872d6dd
commit c11dbd854f

View File

@ -31,13 +31,34 @@ import { showToast } from 'src/utils/ui';
import { defineComponent } from 'vue';
export default defineComponent({
emits: ['item-selected'],
data() {
return {
timerId: null,
barcode: '',
} as {
timerId: null | ReturnType<typeof setInterval>;
barcode: string;
};
},
mounted() {
document.addEventListener('keydown', this.scanListener);
},
unmounted() {
document.removeEventListener('keydown', this.scanListener);
},
activated() {
document.addEventListener('keydown', this.scanListener);
},
deactivated() {
document.removeEventListener('keydown', this.scanListener);
},
methods: {
handleChange(e: Event) {
const elem = e.target as HTMLInputElement;
this.getItem(elem.value);
this.selectItem(elem.value);
elem.value = '';
},
async getItem(code: string) {
async selectItem(code: string) {
const barcode = code.trim();
if (!/\d{12,}/.test(barcode)) {
return this.error(this.t`Invalid barcode value ${barcode}.`);
@ -53,9 +74,51 @@ export default defineComponent({
return this.error(this.t`Item with barcode ${barcode} not found.`);
}
this.success(this.t`${name} added.`);
this.success(this.t`${name} quantity 1 added.`);
this.$emit('item-selected', name);
},
async scanListener({ key, code }: KeyboardEvent) {
/**
* Based under the assumption that
* - Barcode scanners trigger keydown events
* - Keydown events are triggered quicker than human can
* i.e. at max 20ms between events
* - Keydown events are triggered for barcode digits
* - The sequence of digits might be punctuated by a return
*/
const keyCode = Number(key);
const isEnter = code === 'Enter';
if (Number.isNaN(keyCode) && !isEnter) {
return;
}
if (isEnter) {
return await this.setItemFromBarcode();
}
if (this.timerId !== null) {
clearInterval(this.timerId);
}
this.barcode += key;
this.timerId = setInterval(async () => {
await this.setItemFromBarcode();
this.barcode = '';
}, 20);
},
async setItemFromBarcode() {
if (this.barcode.length < 12) {
return;
}
await this.selectItem(this.barcode);
this.barcode = '';
if (this.timerId !== null) {
clearInterval(this.timerId);
}
},
error(message: string) {
showToast({ type: 'error', message });
},