Browse Source

fix(qr-scanner): robustly handle array/object detection results and guarantee dialog dismissal

- Update QRScannerDialog.vue to handle both array and object detection results in onDetect fallback logic (supports vue-qrcode-reader returning arrays).
- Ensure dialog closes and scan is processed for all detection result shapes.
- Use arrow function for close() to guarantee correct binding with vue-facing-decorator.
- Add enhanced logging for all dialog lifecycle and close/cleanup events.
- In WebDialogQRScanner, use direct mount result (not $refs) for dialogComponent to ensure correct instance.
- Add sessionId and improved logging for dialog open/close/cleanup lifecycle.
qrcode-reboot
Matt Raymer 2 days ago
parent
commit
9dc9878472
  1. 254
      src/components/QRScanner/QRScannerDialog.vue
  2. 43
      src/services/QRScanner/WebDialogQRScanner.ts
  3. 45
      src/utils/LogCollector.ts

254
src/components/QRScanner/QRScannerDialog.vue

@ -228,11 +228,18 @@
>
Cancel
</button>
<button
class="px-4 py-2 bg-gray-500 text-white rounded-md hover:bg-gray-600"
@click="copyLogs"
>
Copy Debug Logs
</button>
</div>
</div>
</div>
</div>
</div>
<div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
</template>
<script lang="ts">
@ -241,11 +248,13 @@ import { QrcodeStream } from "vue-qrcode-reader";
import { QRScannerOptions } from "@/services/QRScanner/types";
import { logger } from "@/utils/logger";
import { Capacitor } from "@capacitor/core";
import { logCollector } from "@/utils/LogCollector";
interface ScanProps {
onScan: (result: string) => void;
onError?: (error: Error) => void;
options?: QRScannerOptions;
onClose?: () => void;
}
interface DetectionResult {
@ -267,6 +276,7 @@ export default class QRScannerDialog extends Vue {
@Prop({ type: Function, required: true }) onScan!: ScanProps["onScan"];
@Prop({ type: Function }) onError?: ScanProps["onError"];
@Prop({ type: Object }) options?: ScanProps["options"];
@Prop({ type: Function }) onClose?: ScanProps["onClose"];
// Version
readonly version = "1.1.0";
@ -285,8 +295,28 @@ export default class QRScannerDialog extends Vue {
preferredCamera: "user" | "environment" = "environment";
initializationStatus = "Checking camera access...";
cameraStatus = "Initializing";
errorMessage = "";
created() {
console.log('[QRScannerDialog] created');
console.log('[QRScannerDialog] Props received:', {
onScan: typeof this.onScan,
onError: typeof this.onError,
options: this.options,
onClose: typeof this.onClose,
});
console.log('[QRScannerDialog] Initial state:', {
visible: this.visible,
error: this.error,
useQRReader: this.useQRReader,
isNativePlatform: this.isNativePlatform,
isInitializing: this.isInitializing,
isScanning: this.isScanning,
preferredCamera: this.preferredCamera,
initializationStatus: this.initializationStatus,
cameraStatus: this.cameraStatus,
errorMessage: this.errorMessage,
});
logger.log("QRScannerDialog platform detection:", {
capacitorNative: Capacitor.isNativePlatform(),
isMobile: __IS_MOBILE__,
@ -299,60 +329,68 @@ export default class QRScannerDialog extends Vue {
navigator.mediaDevices && navigator.mediaDevices.getUserMedia
),
});
// If on native platform, close immediately and don't initialize web scanner
if (this.isNativePlatform) {
logger.log("Closing QR dialog on native platform");
this.$nextTick(() => this.close());
}
}
mounted() {
console.log('[QRScannerDialog] mounted');
// Timer to warn if no QR code detected after 10 seconds
this._scanTimeout = setTimeout(() => {
if (!this.isScanning) {
console.warn('[QRScannerDialog] No QR code detected after 10 seconds');
}
}, 10000);
// Periodic timer to log waiting status every 5 seconds
this._waitingInterval = setInterval(() => {
if (!this.isScanning && this.cameraStatus === 'Active') {
console.log('[QRScannerDialog] Still waiting for QR code detection...');
}
}, 5000);
console.log('[QRScannerDialog] Waiting interval started');
}
beforeUnmount() {
if (this._scanTimeout) {
clearTimeout(this._scanTimeout);
console.log('[QRScannerDialog] Scan timeout cleared');
}
if (this._waitingInterval) {
clearInterval(this._waitingInterval);
console.log('[QRScannerDialog] Waiting interval cleared');
}
console.log('[QRScannerDialog] beforeUnmount');
}
async onInit(promise: Promise<void>): Promise<void> {
console.log('[QRScannerDialog] onInit called');
if (this.isNativePlatform) {
logger.log("Closing QR dialog on native platform");
this.$nextTick(() => this.close());
return;
}
this.isInitializing = true;
console.log('[QRScannerDialog] isInitializing set to', this.isInitializing);
this.error = null;
this.initializationStatus = "Checking camera access...";
console.log('[QRScannerDialog] initializationStatus set to', this.initializationStatus);
try {
// First check if mediaDevices API is available
if (!navigator.mediaDevices) {
console.log('[QRScannerDialog] Camera API not available');
throw new Error(
"Camera API not available. Please ensure you're using HTTPS.",
);
}
// Check for video devices
const devices = await navigator.mediaDevices.enumerateDevices();
const videoDevices = devices.filter(
(device) => device.kind === "videoinput",
);
const videoDevices = devices.filter((device) => device.kind === "videoinput");
console.log('[QRScannerDialog] videoDevices found:', videoDevices.length);
if (videoDevices.length === 0) {
throw new Error("No camera found on this device");
}
logger.log("Starting QR scanner initialization...", {
mediaDevices: !!navigator.mediaDevices,
getUserMedia: !!(
navigator.mediaDevices && navigator.mediaDevices.getUserMedia
),
videoDevices: videoDevices.length,
constraints: {
video: {
facingMode: this.preferredCamera,
width: { ideal: 1280 },
height: { ideal: 720 },
},
},
});
// Explicitly request camera permission first
this.initializationStatus = "Requesting camera permission...";
console.log('[QRScannerDialog] initializationStatus set to', this.initializationStatus);
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: {
@ -361,19 +399,12 @@ export default class QRScannerDialog extends Vue {
height: { ideal: 720 },
},
});
// Stop the test stream immediately
stream.getTracks().forEach((track) => track.stop());
this.initializationStatus = "Camera permission granted...";
logger.log("Camera permission granted");
console.log('[QRScannerDialog] initializationStatus set to', this.initializationStatus);
} catch (permissionError) {
const error = permissionError as Error;
logger.error("Camera permission error:", {
name: error.name,
message: error.message,
});
console.log('[QRScannerDialog] Camera permission error:', error.name, error.message);
if (
error.name === "NotAllowedError" ||
error.name === "PermissionDeniedError"
@ -397,62 +428,79 @@ export default class QRScannerDialog extends Vue {
throw new Error(`Camera error: ${error.message}`);
}
}
// Now initialize the QR scanner
this.initializationStatus = "Starting QR scanner...";
logger.log("Initializing QR scanner...");
console.log('[QRScannerDialog] initializationStatus set to', this.initializationStatus);
await promise;
this.isInitializing = false;
this.cameraStatus = "Ready";
logger.log("QR scanner initialized successfully");
console.log('[QRScannerDialog] QR scanner initialized successfully');
console.log('[QRScannerDialog] cameraStatus set to', this.cameraStatus);
} catch (error) {
const wrappedError =
error instanceof Error ? error : new Error(String(error));
const wrappedError = error instanceof Error ? error : new Error(String(error));
this.error = wrappedError.message;
this.cameraStatus = "Error";
console.log('[QRScannerDialog] Error initializing QR scanner:', wrappedError.message);
console.log('[QRScannerDialog] cameraStatus set to', this.cameraStatus);
if (this.onError) {
this.onError(wrappedError);
}
logger.error("Error initializing QR scanner:", {
error: wrappedError.message,
stack: wrappedError.stack,
name: wrappedError.name,
type: wrappedError.constructor.name,
});
} finally {
this.isInitializing = false;
console.log('[QRScannerDialog] isInitializing set to', this.isInitializing);
}
}
onCameraOn(): void {
this.cameraStatus = "Active";
logger.log("Camera turned on successfully");
console.log('[QRScannerDialog] Camera turned on successfully');
console.log('[QRScannerDialog] cameraStatus set to', this.cameraStatus);
}
onCameraOff(): void {
this.cameraStatus = "Off";
logger.log("Camera turned off");
console.log('[QRScannerDialog] Camera turned off');
console.log('[QRScannerDialog] cameraStatus set to', this.cameraStatus);
}
onDetect(result: DetectionResult | Promise<DetectionResult>): void {
const ts = new Date().toISOString();
console.log(`[QRScannerDialog] onDetect called at ${ts} with`, result);
this.isScanning = true;
this.cameraStatus = "Detecting";
logger.log("QR code detected, processing...");
// Handle both promise and direct value cases
const processResult = (detection: DetectionResult) => {
console.log('[QRScannerDialog] isScanning set to', this.isScanning);
console.log('[QRScannerDialog] cameraStatus set to', this.cameraStatus);
const processResult = (detection: DetectionResult | DetectionResult[]) => {
try {
console.log(`[QRScannerDialog] onDetect exit at ${new Date().toISOString()} with detection:`, detection);
// Fallback: If detection is an array, check the first element
let rawValue: string | undefined;
if (Array.isArray(detection) && detection.length > 0 && 'rawValue' in detection[0]) {
rawValue = detection[0].rawValue;
} else if (detection && typeof detection === 'object' && 'rawValue' in detection && detection.rawValue) {
rawValue = (detection as any).rawValue;
}
if (rawValue) {
console.log('[QRScannerDialog] Fallback: Detected rawValue, treating as scan:', rawValue);
this.isInitializing = false;
this.initializationStatus = 'QR code captured!';
this.onScan(rawValue);
try {
logger.log("QR code processed successfully:", detection);
console.log('[QRScannerDialog] About to call close() after scan');
this.close();
console.log('[QRScannerDialog] close() called successfully after scan');
} catch (err) {
console.error('[QRScannerDialog] Error calling close():', err);
}
}
} catch (error) {
this.handleError(error);
} finally {
this.isScanning = false;
this.cameraStatus = "Active";
console.log('[QRScannerDialog] isScanning set to', this.isScanning);
console.log('[QRScannerDialog] cameraStatus set to', this.cameraStatus);
}
};
// Use instanceof Promise for type narrowing
if (result instanceof Promise) {
result
.then(processResult)
@ -460,6 +508,8 @@ export default class QRScannerDialog extends Vue {
.finally(() => {
this.isScanning = false;
this.cameraStatus = "Active";
console.log('[QRScannerDialog] isScanning set to', this.isScanning);
console.log('[QRScannerDialog] cameraStatus set to', this.cameraStatus);
});
} else {
processResult(result);
@ -467,50 +517,104 @@ export default class QRScannerDialog extends Vue {
}
private handleError(error: unknown): void {
const wrappedError =
error instanceof Error ? error : new Error(String(error));
const wrappedError = error instanceof Error ? error : new Error(String(error));
this.error = wrappedError.message;
this.cameraStatus = "Error";
console.log('[QRScannerDialog] handleError:', wrappedError.message);
console.log('[QRScannerDialog] cameraStatus set to', this.cameraStatus);
if (this.onError) {
this.onError(wrappedError);
}
logger.error("QR scanner error:", {
error: wrappedError.message,
stack: wrappedError.stack,
name: wrappedError.name,
type: wrappedError.constructor.name,
});
}
onDecode(result: string): void {
logger.log("QR code decoded:", result);
const ts = new Date().toISOString();
console.log(`[QRScannerDialog] onDecode called at ${ts} with result:`, result);
try {
this.isInitializing = false;
this.initializationStatus = 'QR code captured!';
console.log('[QRScannerDialog] UI state updated after scan: isInitializing set to', this.isInitializing, ', initializationStatus set to', this.initializationStatus);
this.onScan(result);
this.close();
console.log(`[QRScannerDialog] onDecode exit at ${new Date().toISOString()}`);
} catch (error) {
this.handleError(error);
}
}
toggleCamera(): void {
this.preferredCamera =
this.preferredCamera === "user" ? "environment" : "user";
const prevCamera = this.preferredCamera;
this.preferredCamera = this.preferredCamera === "user" ? "environment" : "user";
console.log('[QRScannerDialog] toggleCamera from', prevCamera, 'to', this.preferredCamera);
console.log('[QRScannerDialog] preferredCamera set to', this.preferredCamera);
}
retryScanning(): void {
console.log('[QRScannerDialog] retryScanning called');
this.error = null;
this.isInitializing = true;
// The QR scanner component will automatically reinitialize
console.log('[QRScannerDialog] isInitializing set to', this.isInitializing);
console.log('[QRScannerDialog] Scanning re-initialized');
}
async close(): Promise<void> {
logger.log("Closing QR scanner dialog");
close = async (): Promise<void> => {
console.log('[QRScannerDialog] close called');
this.visible = false;
console.log('[QRScannerDialog] visible set to', this.visible);
// Notify parent/service
if (typeof this.onClose === 'function') {
console.log('[QRScannerDialog] Calling onClose prop');
this.onClose();
}
await this.$nextTick();
if (this.$el && this.$el.parentNode) {
this.$el.parentNode.removeChild(this.$el);
console.log('[QRScannerDialog] Dialog element removed from DOM');
} else {
console.log('[QRScannerDialog] Dialog element NOT removed from DOM');
}
}
onScanDetect(promisedResult) {
const ts = new Date().toISOString();
console.log(`[QRScannerDialog] onScanDetect called at ${ts} with`, promisedResult);
promisedResult
.then((result) => {
console.log(`[QRScannerDialog] onScanDetect exit at ${new Date().toISOString()} with result:`, result);
this.onScan(result);
})
.catch((error) => {
console.error(`[QRScannerDialog] onScanDetect error at ${new Date().toISOString()}:`, error);
this.errorMessage = error.message || 'Scan error';
if (this.onError) this.onError(error);
});
}
onScanError(error) {
const ts = new Date().toISOString();
console.error(`[QRScannerDialog] onScanError called at ${ts}:`, error);
this.errorMessage = error.message || 'Camera error';
if (this.onError) this.onError(error);
}
async startMobileScan() {
try {
console.log('[QRScannerDialog] startMobileScan called');
const scanner = QRScannerFactory.getInstance();
await scanner.startScan();
} catch (error) {
console.error('[QRScannerDialog] Error starting mobile scan:', error);
if (this.onError) this.onError(error);
}
}
async copyLogs() {
console.log('[QRScannerDialog] copyLogs called');
try {
await navigator.clipboard.writeText(logCollector.getLogs());
alert('Logs copied to clipboard!');
} catch (e) {
alert('Failed to copy logs: ' + (e instanceof Error ? e.message : e));
}
}
}

43
src/services/QRScanner/WebDialogQRScanner.ts

@ -9,19 +9,21 @@ export class WebDialogQRScanner implements QRScannerService {
private scanListener: ScanListener | null = null;
private isScanning = false;
private container: HTMLElement | null = null;
private sessionId: number | null = null;
private failsafeTimeout: any = null;
constructor(private options?: QRScannerOptions) {}
async checkPermissions(): Promise<boolean> {
try {
console.log("[QRScanner] Checking camera permissions...");
const permissions = await navigator.permissions.query({
name: "camera" as PermissionName,
});
console.log("[QRScanner] Permission state:", permissions.state);
return permissions.state === "granted";
} catch (error) {
const wrappedError =
error instanceof Error ? error : new Error(String(error));
logger.error("Error checking camera permissions:", wrappedError);
console.error("[QRScanner] Error checking camera permissions:", error);
return false;
}
}
@ -126,6 +128,8 @@ export class WebDialogQRScanner implements QRScannerService {
try {
this.isScanning = true;
this.sessionId = Date.now();
console.log(`[WebDialogQRScanner] Opening dialog, session: ${this.sessionId}`);
// Create and mount dialog component
this.container = document.createElement("div");
@ -142,11 +146,24 @@ export class WebDialogQRScanner implements QRScannerService {
this.scanListener.onError(error);
}
},
onClose: () => {
console.log(`[WebDialogQRScanner] onClose received from dialog, session: ${this.sessionId}`);
this.stopScan('dialog onClose');
},
options: this.options,
sessionId: this.sessionId,
});
this.dialogComponent = this.dialogInstance.mount(this.container).$refs
.dialog as InstanceType<typeof QRScannerDialog>;
this.dialogComponent = this.dialogInstance.mount(this.container) as InstanceType<typeof QRScannerDialog>;
// Failsafe: force cleanup after 60s if dialog is still open
this.failsafeTimeout = setTimeout(() => {
if (this.isScanning) {
console.warn(`[WebDialogQRScanner] Failsafe triggered, forcing cleanup for session: ${this.sessionId}`);
this.stopScan('failsafe timeout');
}
}, 60000);
console.log(`[WebDialogQRScanner] Failsafe timeout set for session: ${this.sessionId}`);
} catch (error) {
this.isScanning = false;
const wrappedError =
@ -160,17 +177,20 @@ export class WebDialogQRScanner implements QRScannerService {
}
}
async stopScan(): Promise<void> {
async stopScan(reason: string = 'manual') : Promise<void> {
if (!this.isScanning) {
return;
}
try {
console.log(`[WebDialogQRScanner] stopScan called, reason: ${reason}, session: ${this.sessionId}`);
if (this.dialogComponent) {
await this.dialogComponent.close();
console.log(`[WebDialogQRScanner] dialogComponent.close() called, session: ${this.sessionId}`);
}
if (this.dialogInstance) {
this.dialogInstance.unmount();
console.log(`[WebDialogQRScanner] dialogInstance.unmount() called, session: ${this.sessionId}`);
}
} catch (error) {
const wrappedError =
@ -179,6 +199,11 @@ export class WebDialogQRScanner implements QRScannerService {
throw wrappedError;
} finally {
this.isScanning = false;
if (this.failsafeTimeout) {
clearTimeout(this.failsafeTimeout);
this.failsafeTimeout = null;
console.log(`[WebDialogQRScanner] Failsafe timeout cleared, session: ${this.sessionId}`);
}
this.cleanupContainer();
}
}
@ -190,13 +215,16 @@ export class WebDialogQRScanner implements QRScannerService {
private cleanupContainer(): void {
if (this.container && this.container.parentNode) {
this.container.parentNode.removeChild(this.container);
console.log(`[WebDialogQRScanner] Dialog container removed from DOM, session: ${this.sessionId}`);
} else {
console.log(`[WebDialogQRScanner] Dialog container NOT removed from DOM, session: ${this.sessionId}`);
}
this.container = null;
}
async cleanup(): Promise<void> {
try {
await this.stopScan();
await this.stopScan('cleanup');
} catch (error) {
const wrappedError =
error instanceof Error ? error : new Error(String(error));
@ -207,6 +235,7 @@ export class WebDialogQRScanner implements QRScannerService {
this.dialogInstance = null;
this.scanListener = null;
this.cleanupContainer();
this.sessionId = null;
}
}
}

45
src/utils/LogCollector.ts

@ -0,0 +1,45 @@
type LogLevel = "log" | "info" | "warn" | "error";
interface LogEntry {
level: LogLevel;
message: any[];
timestamp: string;
}
class LogCollector {
private logs: LogEntry[] = [];
private originalConsole: Partial<
Record<LogLevel, (..._args: any[]) => void>
> = {};
constructor() {
(["log", "info", "warn", "error"] as LogLevel[]).forEach((level) => {
this.originalConsole[level] = console[level];
console[level] = (..._args: any[]) => {
this.logs.push({
level,
message: _args,
timestamp: new Date().toISOString(),
});
this.originalConsole[level]?.apply(console, _args);
};
});
}
getLogs(): string {
return this.logs
.map(
(entry) =>
`[${entry.timestamp}] [${entry.level.toUpperCase()}] ${entry.message
.map((m) => (typeof m === "object" ? JSON.stringify(m) : String(m)))
.join(" ")}`,
)
.join("\n");
}
clear() {
this.logs = [];
}
}
export const logCollector = new LogCollector();
Loading…
Cancel
Save