import React, { useState, useRef, useEffect } from "react"; import ReactDOM from "react-dom"; export default function SignatureCapture({ onSave, onClose, title }) { const [mode, setMode] = useState("draw"); const [typedName, setTypedName] = useState(""); const [signerName, setSignerName] = useState(""); const canvasRef = useRef(null); const isDrawing = useRef(false); useEffect(() => { if (mode === "draw" && canvasRef.current) { const canvas = canvasRef.current; const ctx = canvas.getContext("2d"); ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.strokeStyle = "#333"; ctx.lineWidth = 2; ctx.lineCap = "round"; } }, [mode]); const getPos = (e) => { const rect = canvasRef.current.getBoundingClientRect(); const touch = e.touches ? e.touches[0] : e; return { x: touch.clientX - rect.left, y: touch.clientY - rect.top }; }; const startDraw = (e) => { e.preventDefault(); isDrawing.current = true; const ctx = canvasRef.current.getContext("2d"); const pos = getPos(e); ctx.beginPath(); ctx.moveTo(pos.x, pos.y); }; const draw = (e) => { e.preventDefault(); if (!isDrawing.current) return; const ctx = canvasRef.current.getContext("2d"); const pos = getPos(e); ctx.lineTo(pos.x, pos.y); ctx.stroke(); }; const stopDraw = () => { isDrawing.current = false; }; const clearCanvas = () => { const ctx = canvasRef.current.getContext("2d"); ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, canvasRef.current.width, canvasRef.current.height); }; const handleSave = () => { if (!signerName.trim()) return; if (mode === "draw") { const dataUrl = canvasRef.current.toDataURL("image/png"); onSave(dataUrl, "drawn", signerName.trim()); } else { onSave(typedName, "typed", signerName.trim()); } }; return ReactDOM.createPortal(
e.stopPropagation()}>

{title || "Capture Signature"}

setSignerName(e.target.value)} placeholder="Enter signer's full name" />
{mode === "draw" ? (
) : (
setTypedName(e.target.value)} placeholder="Type your name" /> {typedName &&
{typedName}
}
)}
, document.body ); }