Implement wizard-style scanner with auto-scanning (Part 1)
🧙♂️ Scanner Wizard Components: - ScanModeSelector: Choose between 4 scan modes with beautiful UI • Add to Database, Search Collections, Price Check, Deck Building • Hover effects and responsive grid layout • Pro tips section with usage guidance 📷 Auto-Scanning Camera: - AutoScanningCamera: 2-3 second stabilization with countdown - Simulated card detection every 2 seconds - 5-second minimum between scans to prevent rapid scanning - Queue counter (0/100) and duplicate detection - Manual scan fallback button 🎯 Scanning Toast: - Top-aligned toast notification matching screenshot style - Progress bar during stabilization countdown - Different states: scanning, processing, success, error - Smooth slide-down animation ✨ Features: - Queue management up to 100 cards - Recent scan deduplication (keeps last 10) - Visual feedback with scanning overlay - Image caching with canvas capture - Error handling and recovery Next: Card queue review stage with bulk operations
This commit is contained in:
parent
24535e4e26
commit
8209566451
4 changed files with 540 additions and 0 deletions
351
src/components/scanner/AutoScanningCamera.tsx
Normal file
351
src/components/scanner/AutoScanningCamera.tsx
Normal file
|
|
@ -0,0 +1,351 @@
|
|||
import React, { useRef, useState, useEffect, useCallback } from 'react';
|
||||
import ScanningToast from './ScanningToast';
|
||||
import { aiCardOCR, type CardOCRResult } from '../../services/aiOcr';
|
||||
|
||||
interface ScannedCard {
|
||||
id: string;
|
||||
cardData: CardOCRResult;
|
||||
imageDataUrl: string;
|
||||
timestamp: number;
|
||||
queuePosition: number;
|
||||
}
|
||||
|
||||
interface AutoScanningCameraProps {
|
||||
onCardScanned: (card: ScannedCard) => void;
|
||||
onError: (error: string) => void;
|
||||
isActive: boolean;
|
||||
maxQueueSize?: number;
|
||||
}
|
||||
|
||||
const AutoScanningCamera: React.FC<AutoScanningCameraProps> = ({
|
||||
onCardScanned,
|
||||
onError,
|
||||
isActive,
|
||||
maxQueueSize = 100
|
||||
}) => {
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const streamRef = useRef<MediaStream | null>(null);
|
||||
const scanTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const lastScanTimeRef = useRef<number>(0);
|
||||
|
||||
const [isStreaming, setIsStreaming] = useState(false);
|
||||
const [scanState, setScanState] = useState<{
|
||||
isScanning: boolean;
|
||||
isProcessing: boolean;
|
||||
message: string;
|
||||
countdown: number;
|
||||
}>({
|
||||
isScanning: false,
|
||||
isProcessing: false,
|
||||
message: '',
|
||||
countdown: 0
|
||||
});
|
||||
|
||||
const [queueCount, setQueueCount] = useState(0);
|
||||
const [recentScans, setRecentScans] = useState<Set<string>>(new Set());
|
||||
|
||||
// Initialize camera
|
||||
useEffect(() => {
|
||||
if (isActive) {
|
||||
startCamera();
|
||||
} else {
|
||||
stopCamera();
|
||||
}
|
||||
|
||||
return () => {
|
||||
stopCamera();
|
||||
};
|
||||
}, [isActive]);
|
||||
|
||||
// Auto-scan detection
|
||||
useEffect(() => {
|
||||
if (!isStreaming || !isActive) return;
|
||||
|
||||
const detectCardStabilization = () => {
|
||||
if (scanState.isProcessing || queueCount >= maxQueueSize) return;
|
||||
|
||||
// Clear existing timeout
|
||||
if (scanTimeoutRef.current) {
|
||||
clearTimeout(scanTimeoutRef.current);
|
||||
}
|
||||
|
||||
// Start countdown
|
||||
setScanState(prev => ({
|
||||
...prev,
|
||||
isScanning: true,
|
||||
message: 'Card detected, stabilizing...',
|
||||
countdown: 3
|
||||
}));
|
||||
|
||||
let countdown = 3;
|
||||
const countdownInterval = setInterval(() => {
|
||||
countdown--;
|
||||
setScanState(prev => ({
|
||||
...prev,
|
||||
countdown,
|
||||
message: countdown > 0 ? `Scanning in ${countdown}...` : 'Scanning card...'
|
||||
}));
|
||||
|
||||
if (countdown <= 0) {
|
||||
clearInterval(countdownInterval);
|
||||
triggerScan();
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
// Set timeout for actual scan
|
||||
scanTimeoutRef.current = setTimeout(() => {
|
||||
clearInterval(countdownInterval);
|
||||
triggerScan();
|
||||
}, 3000);
|
||||
};
|
||||
|
||||
// Simulate card detection (in real implementation, this would use computer vision)
|
||||
const detectionInterval = setInterval(() => {
|
||||
// Only trigger if enough time has passed since last scan (prevent rapid scanning)
|
||||
const now = Date.now();
|
||||
if (now - lastScanTimeRef.current > 5000) { // 5 second minimum between scans
|
||||
detectCardStabilization();
|
||||
}
|
||||
}, 2000);
|
||||
|
||||
return () => {
|
||||
clearInterval(detectionInterval);
|
||||
if (scanTimeoutRef.current) {
|
||||
clearTimeout(scanTimeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, [isStreaming, isActive, scanState.isProcessing, queueCount, maxQueueSize]);
|
||||
|
||||
const startCamera = async () => {
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
video: {
|
||||
facingMode: 'environment',
|
||||
width: { ideal: 1920 },
|
||||
height: { ideal: 1080 }
|
||||
}
|
||||
});
|
||||
|
||||
if (videoRef.current) {
|
||||
videoRef.current.srcObject = stream;
|
||||
streamRef.current = stream;
|
||||
|
||||
videoRef.current.onloadedmetadata = () => {
|
||||
videoRef.current?.play().then(() => {
|
||||
setIsStreaming(true);
|
||||
});
|
||||
};
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('Camera error:', err);
|
||||
onError(`Camera access failed: ${err.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
const stopCamera = () => {
|
||||
if (streamRef.current) {
|
||||
streamRef.current.getTracks().forEach(track => track.stop());
|
||||
streamRef.current = null;
|
||||
}
|
||||
setIsStreaming(false);
|
||||
setScanState({
|
||||
isScanning: false,
|
||||
isProcessing: false,
|
||||
message: '',
|
||||
countdown: 0
|
||||
});
|
||||
};
|
||||
|
||||
const captureImage = useCallback((): string | null => {
|
||||
if (!videoRef.current || !canvasRef.current) return null;
|
||||
|
||||
const video = videoRef.current;
|
||||
const canvas = canvasRef.current;
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
if (!ctx) return null;
|
||||
|
||||
// Set canvas dimensions to match video
|
||||
canvas.width = video.videoWidth;
|
||||
canvas.height = video.videoHeight;
|
||||
|
||||
// Draw current video frame to canvas
|
||||
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||||
|
||||
// Return image data URL
|
||||
return canvas.toDataURL('image/jpeg', 0.8);
|
||||
}, []);
|
||||
|
||||
const triggerScan = useCallback(async () => {
|
||||
if (scanState.isProcessing || queueCount >= maxQueueSize) return;
|
||||
|
||||
setScanState(prev => ({
|
||||
...prev,
|
||||
isScanning: false,
|
||||
isProcessing: true,
|
||||
message: 'Processing card with AI...',
|
||||
countdown: 0
|
||||
}));
|
||||
|
||||
try {
|
||||
const imageDataUrl = captureImage();
|
||||
if (!imageDataUrl) {
|
||||
throw new Error('Failed to capture image');
|
||||
}
|
||||
|
||||
// Process with AI OCR
|
||||
const cardData = await aiCardOCR.analyzeCard(imageDataUrl);
|
||||
|
||||
// Create unique ID for this scan
|
||||
const cardId = `scan_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||
|
||||
// Check for recent duplicates (simple hash of card name)
|
||||
const cardHash = (cardData.cardName || 'unknown').toLowerCase().replace(/\s+/g, '');
|
||||
const isRecentDuplicate = recentScans.has(cardHash);
|
||||
|
||||
if (isRecentDuplicate) {
|
||||
setScanState(prev => ({
|
||||
...prev,
|
||||
isProcessing: false,
|
||||
message: `Duplicate detected: ${cardData.cardName || 'Unknown Card'}`,
|
||||
}));
|
||||
} else {
|
||||
// Add to recent scans (keep last 10)
|
||||
setRecentScans(prev => {
|
||||
const newSet = new Set(prev);
|
||||
newSet.add(cardHash);
|
||||
if (newSet.size > 10) {
|
||||
const firstKey = newSet.values().next().value;
|
||||
newSet.delete(firstKey);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
|
||||
// Create scanned card
|
||||
const scannedCard: ScannedCard = {
|
||||
id: cardId,
|
||||
cardData,
|
||||
imageDataUrl,
|
||||
timestamp: Date.now(),
|
||||
queuePosition: queueCount + 1
|
||||
};
|
||||
|
||||
// Add to queue
|
||||
onCardScanned(scannedCard);
|
||||
setQueueCount(prev => prev + 1);
|
||||
lastScanTimeRef.current = Date.now();
|
||||
|
||||
setScanState(prev => ({
|
||||
...prev,
|
||||
isProcessing: false,
|
||||
message: `Added: ${cardData.cardName || 'Unknown Card'}`,
|
||||
}));
|
||||
}
|
||||
|
||||
// Clear message after 2 seconds
|
||||
setTimeout(() => {
|
||||
setScanState(prev => ({
|
||||
...prev,
|
||||
message: '',
|
||||
}));
|
||||
}, 2000);
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Scan processing error:', error);
|
||||
setScanState(prev => ({
|
||||
...prev,
|
||||
isProcessing: false,
|
||||
message: 'Scan failed, try again',
|
||||
}));
|
||||
|
||||
setTimeout(() => {
|
||||
setScanState(prev => ({
|
||||
...prev,
|
||||
message: '',
|
||||
}));
|
||||
}, 3000);
|
||||
}
|
||||
}, [captureImage, onCardScanned, queueCount, maxQueueSize, recentScans, scanState.isProcessing]);
|
||||
|
||||
const manualScan = () => {
|
||||
if (!scanState.isProcessing && queueCount < maxQueueSize) {
|
||||
triggerScan();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
{/* Scanning Toast */}
|
||||
<ScanningToast
|
||||
isVisible={scanState.isScanning || scanState.isProcessing || !!scanState.message}
|
||||
message={scanState.message}
|
||||
progress={scanState.isScanning ? ((3 - scanState.countdown) / 3) * 100 : undefined}
|
||||
type={scanState.isProcessing ? 'processing' : scanState.message.includes('Added:') ? 'success' : 'scanning'}
|
||||
/>
|
||||
|
||||
{/* Camera Preview */}
|
||||
<div className="relative bg-black rounded-lg overflow-hidden">
|
||||
<video
|
||||
ref={videoRef}
|
||||
autoPlay
|
||||
playsInline
|
||||
muted
|
||||
className="w-full h-auto max-h-96 object-cover"
|
||||
style={{ minHeight: '300px' }}
|
||||
/>
|
||||
|
||||
{/* Scan Guide Overlay */}
|
||||
{isStreaming && (
|
||||
<div className="absolute inset-0 pointer-events-none">
|
||||
{/* Card frame guide */}
|
||||
<div className="absolute inset-4 border-2 border-white border-dashed rounded-lg flex items-center justify-center">
|
||||
<div className="bg-black bg-opacity-50 text-white px-4 py-2 rounded-lg text-sm text-center">
|
||||
<div className="font-medium">Position card within this area</div>
|
||||
<div className="text-xs opacity-75">Auto-scan in 2-3 seconds</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Queue counter */}
|
||||
<div className="absolute top-4 right-4 bg-blue-600 text-white px-3 py-1 rounded-full text-sm font-medium">
|
||||
Queue: {queueCount}/{maxQueueSize}
|
||||
</div>
|
||||
|
||||
{/* Scanning indicator */}
|
||||
{scanState.isScanning && (
|
||||
<div className="absolute inset-0 bg-blue-500 bg-opacity-20 border-2 border-blue-500 rounded-lg animate-pulse" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Placeholder when not streaming */}
|
||||
{!isStreaming && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className="text-white text-center">
|
||||
<div className="text-4xl mb-2">📹</div>
|
||||
<div className="font-medium">Starting Camera...</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Hidden canvas for image capture */}
|
||||
<canvas ref={canvasRef} className="hidden" />
|
||||
|
||||
{/* Manual scan button */}
|
||||
{isStreaming && (
|
||||
<div className="mt-4 text-center">
|
||||
<button
|
||||
onClick={manualScan}
|
||||
disabled={scanState.isProcessing || queueCount >= maxQueueSize}
|
||||
className="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white px-6 py-2 rounded-lg font-medium transition-colors"
|
||||
>
|
||||
{scanState.isProcessing ? 'Processing...' : 'Manual Scan'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AutoScanningCamera;
|
||||
89
src/components/scanner/ScanModeSelector.tsx
Normal file
89
src/components/scanner/ScanModeSelector.tsx
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
import React from 'react';
|
||||
|
||||
interface ScanMode {
|
||||
id: 'add-to-database' | 'search-collections' | 'price-check' | 'deck-building';
|
||||
title: string;
|
||||
description: string;
|
||||
icon: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
interface ScanModeSelectorProps {
|
||||
onModeSelect: (mode: ScanMode['id']) => void;
|
||||
}
|
||||
|
||||
const ScanModeSelector: React.FC<ScanModeSelectorProps> = ({ onModeSelect }) => {
|
||||
const scanModes: ScanMode[] = [
|
||||
{
|
||||
id: 'add-to-database',
|
||||
title: 'Add Cards to Database',
|
||||
description: 'Scan new cards and add them to your collections',
|
||||
icon: '📚',
|
||||
color: 'bg-blue-500 hover:bg-blue-600'
|
||||
},
|
||||
{
|
||||
id: 'search-collections',
|
||||
title: 'Search Collections',
|
||||
description: 'Find these cards in your existing collections',
|
||||
icon: '🔍',
|
||||
color: 'bg-green-500 hover:bg-green-600'
|
||||
},
|
||||
{
|
||||
id: 'price-check',
|
||||
title: 'Price Check',
|
||||
description: 'Get real-time pricing for your cards',
|
||||
icon: '💰',
|
||||
color: 'bg-yellow-500 hover:bg-yellow-600'
|
||||
},
|
||||
{
|
||||
id: 'deck-building',
|
||||
title: 'Deck Building',
|
||||
description: 'Scan cards directly into a deck with legality checks',
|
||||
icon: '🎯',
|
||||
color: 'bg-purple-500 hover:bg-purple-600'
|
||||
}
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto p-6">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-2">Card Scanner</h1>
|
||||
<p className="text-gray-600">Choose your scanning mode to get started</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{scanModes.map((mode) => (
|
||||
<button
|
||||
key={mode.id}
|
||||
onClick={() => onModeSelect(mode.id)}
|
||||
className={`${mode.color} text-white p-6 rounded-lg shadow-lg transition-all duration-200 hover:shadow-xl hover:scale-105 text-left`}
|
||||
>
|
||||
<div className="flex items-start space-x-4">
|
||||
<div className="text-3xl">{mode.icon}</div>
|
||||
<div className="flex-1">
|
||||
<h3 className="text-xl font-semibold mb-2">{mode.title}</h3>
|
||||
<p className="text-white/90 text-sm leading-relaxed">
|
||||
{mode.description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mt-8 text-center">
|
||||
<div className="bg-gray-50 rounded-lg p-4 text-sm text-gray-600">
|
||||
<p className="font-medium mb-2">💡 Pro Tips:</p>
|
||||
<ul className="space-y-1 text-left max-w-md mx-auto">
|
||||
<li>• Position cards clearly within the camera frame</li>
|
||||
<li>• Scanner will auto-detect cards after 2-3 seconds</li>
|
||||
<li>• You can scan up to 100 cards in a single session</li>
|
||||
<li>• Duplicates are allowed and will be tracked separately</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ScanModeSelector;
|
||||
84
src/components/scanner/ScanningToast.tsx
Normal file
84
src/components/scanner/ScanningToast.tsx
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import React from 'react';
|
||||
|
||||
interface ScanningToastProps {
|
||||
isVisible: boolean;
|
||||
message: string;
|
||||
progress?: number; // 0-100 for progress bar
|
||||
type?: 'scanning' | 'processing' | 'success' | 'error';
|
||||
}
|
||||
|
||||
const ScanningToast: React.FC<ScanningToastProps> = ({
|
||||
isVisible,
|
||||
message,
|
||||
progress,
|
||||
type = 'scanning'
|
||||
}) => {
|
||||
if (!isVisible) return null;
|
||||
|
||||
const getTypeStyles = () => {
|
||||
switch (type) {
|
||||
case 'scanning':
|
||||
return 'bg-blue-600 text-white';
|
||||
case 'processing':
|
||||
return 'bg-purple-600 text-white';
|
||||
case 'success':
|
||||
return 'bg-green-600 text-white';
|
||||
case 'error':
|
||||
return 'bg-red-600 text-white';
|
||||
default:
|
||||
return 'bg-blue-600 text-white';
|
||||
}
|
||||
};
|
||||
|
||||
const getIcon = () => {
|
||||
switch (type) {
|
||||
case 'scanning':
|
||||
return '📷';
|
||||
case 'processing':
|
||||
return '🤖';
|
||||
case 'success':
|
||||
return '✅';
|
||||
case 'error':
|
||||
return '❌';
|
||||
default:
|
||||
return '📷';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed top-4 left-1/2 transform -translate-x-1/2 z-50 animate-slide-down">
|
||||
<div className={`${getTypeStyles()} rounded-lg shadow-lg px-4 py-3 min-w-80 max-w-md`}>
|
||||
<div className="flex items-center space-x-3">
|
||||
{/* Icon */}
|
||||
<div className="text-lg">{getIcon()}</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1">
|
||||
<div className="font-medium text-sm">{message}</div>
|
||||
|
||||
{/* Progress bar */}
|
||||
{progress !== undefined && (
|
||||
<div className="mt-2">
|
||||
<div className="w-full bg-white/20 rounded-full h-1.5">
|
||||
<div
|
||||
className="bg-white h-1.5 rounded-full transition-all duration-300 ease-out"
|
||||
style={{ width: `${Math.min(100, Math.max(0, progress))}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Spinner for scanning/processing */}
|
||||
{(type === 'scanning' || type === 'processing') && (
|
||||
<div className="w-5 h-5">
|
||||
<div className="animate-spin rounded-full h-5 w-5 border-2 border-white border-t-transparent"></div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ScanningToast;
|
||||
|
|
@ -2,6 +2,22 @@
|
|||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/* Custom animations */
|
||||
@keyframes slide-down {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translate(-50%, -20px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translate(-50%, 0);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-slide-down {
|
||||
animation: slide-down 0.3s ease-out;
|
||||
}
|
||||
|
||||
/* Import custom card effects */
|
||||
@import './styles/cardEffects.css';
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue