优化:支持中文

This commit is contained in:
iqudoo
2026-06-09 11:05:42 +08:00
parent b12497443c
commit 13b461050b

View File

@@ -5,6 +5,28 @@ let _scannerTimer = null;
let _scannerLastInputTime = 0;
const SCANNER_INPUT_INTERVAL = 100;
const SCANNER_IGNORE_KEYS = [
"PageUp",
"PageDown",
"ArrowRight",
"ArrowLeft",
"ArrowDown",
"ArrowUp",
"Unidentified",
"Insert",
"End",
"Home",
"Delete",
"Escape",
"Process",
"Shift",
"Backspace",
"Delete",
"Tab",
"Space",
"Control",
"CapsLock",
];
function getWindow() {
if (typeof window === "undefined") {
@@ -31,8 +53,20 @@ function delayClearScannerValue() {
}, SCANNER_INPUT_INTERVAL);
}
function decodeAltCharCodes(value) {
return value
.replace(/Alt(\d{5})/g, (_match, code) => {
if (code.length < 5) {
return "";
}
return String.fromCharCode(Number(code));
})
.replace(/Alt(\d+)/g, () => "")
.replace(/Alt/g, () => "");
}
function normalizeScannerValue(value) {
return value.replace(/[\uFF01-\uFF5E]/g, char => {
return decodeAltCharCodes(value).replace(/[\uFF01-\uFF5E]/g, char => {
return String.fromCharCode(char.charCodeAt(0) - 0xFEE0);
}).replace(/\u3002/g, ".")
.replace(/\u2014/g, "_");
@@ -64,7 +98,7 @@ function onScannerKeydown(event) {
clearScannerValue();
return;
}
if (event.ctrlKey || event.metaKey || event.altKey) {
if (event.ctrlKey || event.metaKey) {
return;
}
if (event.key === "Enter") {
@@ -78,7 +112,7 @@ function onScannerKeydown(event) {
}
return;
}
if (!event.key || event.key.length !== 1) {
if (!event.key || SCANNER_IGNORE_KEYS.includes(event.key)) {
return;
}
const now = Date.now();
@@ -86,11 +120,12 @@ function onScannerKeydown(event) {
clearScannerValue();
}
_scannerLastInputTime = now;
_scannerValue += event.key;
// 累积按键序列,支持 Alt+数字 编码的中文扫码枪输入
_scannerValue = `${_scannerValue}${event.key}`;
delayClearScannerValue();
}
export function startScanner(callback){
export function startScanner(callback) {
if (!callback || typeof callback !== "function") {
return;
}
@@ -107,7 +142,7 @@ export function startScanner(callback){
win.addEventListener("keydown", onScannerKeydown);
}
export function stopScanner(){
export function stopScanner() {
if (_scannerStatus !== "scanning") {
return;
}