talos-access / frontend /src /components /CameraCapture.tsx
Greg
feat(ta-01): switch between front/back camera in CameraCapture
55f0bbf
Raw History Blame Contribute Delete
8.77 kB
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">&times;</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>
);
}