Spaces:
Runtime error
Runtime error
File size: 8,770 Bytes
6aa6081 55f0bbf 6aa6081 55f0bbf 6aa6081 55f0bbf 6aa6081 55f0bbf 6aa6081 55f0bbf 6aa6081 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | import { useState, useRef, useEffect, useCallback } from 'react';
import { Camera, Check, RotateCcw, SwitchCamera } from 'lucide-react';
interface CameraCaptureProps {
isOpen: boolean;
onCapture: (base64Image: string) => void;
onClose: () => void;
}
export default function CameraCapture({ isOpen, onCapture, onClose }: CameraCaptureProps) {
const videoRef = useRef<HTMLVideoElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const overlayRef = useRef<HTMLCanvasElement>(null);
const streamRef = useRef<MediaStream | null>(null);
const animFrameRef = useRef<number>(0);
const detectorRef = useRef<any>(null);
const [cameraReady, setCameraReady] = useState(false);
const [cameraError, setCameraError] = useState(false);
const [captured, setCaptured] = useState<string | null>(null);
const [hasFaceDetector, setHasFaceDetector] = useState(false);
const [facingMode, setFacingMode] = useState<'user' | 'environment'>('user');
const startCamera = useCallback(async () => {
try {
stopCamera();
const stream = await navigator.mediaDevices.getUserMedia({
video: { width: 640, height: 480, facingMode },
});
streamRef.current = stream;
if (videoRef.current) videoRef.current.srcObject = stream;
setCameraReady(true);
setCameraError(false);
} catch {
setCameraError(true);
}
}, [facingMode]);
const toggleFacing = useCallback(() => {
setFacingMode((m) => (m === 'user' ? 'environment' : 'user'));
}, []);
const stopCamera = useCallback(() => {
cancelAnimationFrame(animFrameRef.current);
if (streamRef.current) {
streamRef.current.getTracks().forEach((t) => t.stop());
streamRef.current = null;
}
setCameraReady(false);
}, []);
const drawGuide = useCallback(() => {
const overlay = overlayRef.current;
const video = videoRef.current;
if (!overlay || !video) return;
overlay.width = video.videoWidth || 640;
overlay.height = video.videoHeight || 480;
const ctx = overlay.getContext('2d');
if (!ctx) return;
ctx.clearRect(0, 0, overlay.width, overlay.height);
const w = overlay.width * 0.5;
const h = overlay.height * 0.55;
const x = (overlay.width - w) / 2;
const y = (overlay.height - h) / 2 - overlay.height * 0.05;
ctx.strokeStyle = '#22c55e';
ctx.lineWidth = 3;
ctx.setLineDash([8, 6]);
ctx.beginPath();
ctx.roundRect(x, y, w, h, 12);
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = 'rgba(34, 197, 94, 0.6)';
ctx.font = '13px sans-serif';
ctx.textAlign = 'center';
ctx.fillText('Coloque su rostro aquí', overlay.width / 2, overlay.height - 20);
}, []);
const startFaceDetection = useCallback(async () => {
if (!('FaceDetector' in window)) {
drawGuide();
return;
}
setHasFaceDetector(true);
try {
detectorRef.current = new (window as any).FaceDetector({
maxDetectedFaces: 3,
fastMode: true,
});
} catch {
drawGuide();
return;
}
const detect = async () => {
const video = videoRef.current;
const overlay = overlayRef.current;
if (!video || !overlay || !detectorRef.current) {
animFrameRef.current = requestAnimationFrame(detect);
return;
}
try {
const faces = await detectorRef.current.detect(video);
const ctx = overlay.getContext('2d');
if (!ctx) return;
overlay.width = video.videoWidth || 640;
overlay.height = video.videoHeight || 480;
ctx.clearRect(0, 0, overlay.width, overlay.height);
if (faces.length > 0) {
for (const face of faces) {
const b = face.boundingBox;
ctx.strokeStyle = '#22c55e';
ctx.lineWidth = 3;
ctx.setLineDash([]);
ctx.beginPath();
ctx.roundRect(b.x, b.y, b.width, b.height, 8);
ctx.stroke();
}
} else {
drawGuide();
}
} catch {
drawGuide();
}
animFrameRef.current = requestAnimationFrame(detect);
};
animFrameRef.current = requestAnimationFrame(detect);
}, [drawGuide]);
useEffect(() => {
if (!isOpen) return;
startCamera();
return () => {
stopCamera();
detectorRef.current = null;
};
}, [isOpen, startCamera, stopCamera]);
useEffect(() => {
if (cameraReady) {
const t = setTimeout(() => startFaceDetection(), 300);
return () => clearTimeout(t);
}
}, [cameraReady, startFaceDetection]);
const handleCapture = () => {
if (!videoRef.current || !canvasRef.current) return;
const video = videoRef.current;
const canvas = canvasRef.current;
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.drawImage(video, 0, 0);
const base64 = canvas.toDataURL('image/jpeg', 0.8);
setCaptured(base64);
stopCamera();
};
const handleAccept = () => {
if (captured) onCapture(captured);
};
const handleRetry = () => {
setCaptured(null);
startCamera();
};
const handleClose = () => {
setCaptured(null);
stopCamera();
onClose();
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[60] p-4" onClick={handleClose}>
<div className="bg-white rounded-2xl shadow-2xl max-w-sm w-full overflow-hidden" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
<h3 className="text-lg font-bold">Capturar Rostro</h3>
<button onClick={handleClose} className="text-gray-400 hover:text-gray-600 text-2xl leading-none">×</button>
</div>
<div className="p-6">
{cameraError ? (
<div className="text-center py-8">
<p className="text-red-500 text-sm mb-4">No se pudo acceder a la cámara</p>
<button onClick={startCamera} className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition text-sm">Reintentar</button>
</div>
) : captured ? (
<div className="space-y-4">
<img src={captured} alt="Rostro capturado" className="w-full rounded-lg" />
<div className="flex gap-2">
<button onClick={handleAccept} className="flex-1 bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition text-sm inline-flex items-center justify-center gap-2"><Check size={16} /> Aceptar</button>
<button onClick={handleRetry} className="flex-1 bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300 transition text-sm inline-flex items-center justify-center gap-2"><RotateCcw size={16} /> Repetir</button>
</div>
</div>
) : (
<div className="space-y-4">
<div className="relative bg-black rounded-lg overflow-hidden">
<video ref={videoRef} autoPlay playsInline className="w-full" />
<canvas ref={overlayRef} className="absolute inset-0 w-full h-full pointer-events-none" />
{!cameraReady && (
<div className="absolute inset-0 flex items-center justify-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-white" />
</div>
)}
</div>
<canvas ref={canvasRef} className="hidden" />
{hasFaceDetector && (
<p className="text-xs text-center text-green-600">Detección facial activa</p>
)}
<div className="flex gap-2">
<button onClick={handleCapture} disabled={!cameraReady}
className="flex-1 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition text-sm inline-flex items-center justify-center gap-2 disabled:opacity-50">
<Camera size={16} /> Tomar foto
</button>
<button onClick={toggleFacing} type="button"
title={facingMode === 'user' ? 'Cambiar a cámara trasera' : 'Cambiar a cámara frontal'}
className="bg-gray-100 text-gray-700 px-3 py-2 rounded-lg hover:bg-gray-200 transition text-sm inline-flex items-center justify-center gap-1.5">
<SwitchCamera size={16} />
<span className="hidden sm:inline">
{facingMode === 'user' ? 'Trasera' : 'Frontal'}
</span>
</button>
</div>
</div>
)}
</div>
</div>
</div>
);
}
|