forked from trent_larson/crowd-funder-for-time-pwa
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.
This commit is contained in:
@@ -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 {
|
||||
logger.log("QR code processed successfully:", detection);
|
||||
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 {
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user