feat: 集成二维码扫描功能,更新相关组件和国际化支持

This commit is contained in:
2025-12-24 04:34:40 +07:00
parent 648ca3edc9
commit 5ff44e4de0
12 changed files with 450 additions and 218 deletions

View File

@@ -1,82 +1,71 @@
import { BarcodeScanner } from "@capacitor-community/barcode-scanner";
import { CapacitorBarcodeScanner } from "@capacitor/barcode-scanner";
import { Capacitor } from "@capacitor/core";
import { toastController } from "@ionic/vue";
export interface QRScanResult {
text: string;
format: string;
rawValue: string;
displayValue: string;
}
export interface ScannerOptions {
title?: string;
}
export function useQRScanner() {
const { t } = useI18n();
const { vibrate } = useHaptics();
const isSupported = Capacitor.isNativePlatform();
// 检查权限
const checkPermission = async (): Promise<boolean> => {
try {
const status = await BarcodeScanner.checkPermission({ force: true });
return status.granted || false;
}
catch (error) {
console.error("Permission check failed:", error);
return false;
}
const showError = async (message: string) => {
const toast = await toastController.create({
message,
duration: 2000,
position: "top",
color: "danger",
});
await toast.present();
};
// 开始扫描
const startScan = async (): Promise<QRScanResult | null> => {
const openScanner = async (options?: ScannerOptions): Promise<QRScanResult | null> => {
try {
// 检查是否为原生平台
if (!isSupported) {
console.warn("QR Scanner is only supported on native platforms");
await showError(t("scanner.notSupported"));
return null;
}
// 检查权限
const hasPermission = await checkPermission();
if (!hasPermission) {
throw new Error("Camera permission denied");
}
vibrate();
// 隐藏背景以显示相机预览
await BarcodeScanner.hideBackground();
const result = await CapacitorBarcodeScanner.scanBarcode({
hint: 0,
scanInstructions: options?.title || t("scanner.hint"),
cameraDirection: 1,
});
// 开始扫描
const result = await BarcodeScanner.startScan();
// 恢复背景
await BarcodeScanner.showBackground();
if (result?.hasContent) {
if (result.ScanResult) {
vibrate();
return {
text: result.content,
format: result.format || "QR_CODE",
text: result.ScanResult,
format: result.format?.toString() || "UNKNOWN",
rawValue: result.ScanResult,
displayValue: result.ScanResult,
};
}
return null;
}
catch (error) {
// 确保恢复背景
await BarcodeScanner.showBackground();
console.error("QR scan failed:", error);
throw error;
}
};
// 停止扫描
const stopScan = async () => {
try {
await BarcodeScanner.stopScan();
await BarcodeScanner.showBackground();
}
catch (error) {
console.error("Stop scan failed:", error);
catch (error: any) {
console.log("error.message", error.message);
if (error.code !== "OS-PLUG-BARC-0006") {
await showError(t("scanner.openError"));
}
return null;
}
};
return {
isSupported,
checkPermission,
startScan,
stopScan,
openScanner,
};
}