import React, { useRef, useState, useEffect } from "react" import { Image } from "@mwater/expressions" import ImagePopupComponent from "../ImagePopupComponent" import RotationAwareImageComponent from "../RotationAwareImageComponent" import { LocalizeString } from "ez-localize" import { ImageAcquirer, ImageManager } from "../formContext" export interface SignatureAnswerComponentProps { /** Current signature image */ signature?: Image | null /** Called when signature changed */ onSignatureChange?: (signature: Image | null) => void imageManager: ImageManager imageAcquirer?: ImageAcquirer T: LocalizeString } interface Point { x: number y: number } /** Component for capturing signatures via drawing on a canvas */ export default function SignatureAnswerComponent(props: SignatureAnswerComponentProps) { const canvasRef = useRef(null) const [isDrawing, setIsDrawing] = useState(false) const [hasDrawn, setHasDrawn] = useState(false) const [isUploading, setIsUploading] = useState(false) const [modalOpen, setModalOpen] = useState(false) const [lastPoint, setLastPoint] = useState(null) // Fixed internal canvas dimensions for consistent resolution const CANVAS_WIDTH = 600 const CANVAS_HEIGHT = 200 // Initialize canvas useEffect(() => { const canvas = canvasRef.current if (!canvas || props.signature) return const ctx = canvas.getContext("2d") if (!ctx) return // Set canvas internal size (fixed resolution) canvas.width = CANVAS_WIDTH canvas.height = CANVAS_HEIGHT // Fill with white background ctx.fillStyle = "#ffffff" ctx.fillRect(0, 0, canvas.width, canvas.height) // Draw placeholder text ctx.fillStyle = "#999999" ctx.font = "18px sans-serif" ctx.textAlign = "center" ctx.textBaseline = "middle" ctx.fillText(props.T("Draw your signature here"), canvas.width / 2, canvas.height / 2) }, [props.signature, props.T]) const getCoordinates = (e: React.MouseEvent | React.TouchEvent): Point | null => { const canvas = canvasRef.current if (!canvas) return null const rect = canvas.getBoundingClientRect() // Get the raw coordinates let clientX: number, clientY: number if ('touches' in e) { // Touch event if (e.touches.length === 0) return null clientX = e.touches[0].clientX clientY = e.touches[0].clientY } else { // Mouse event clientX = e.clientX clientY = e.clientY } // Calculate coordinates relative to canvas element const x = clientX - rect.left const y = clientY - rect.top // Scale coordinates to match internal canvas resolution const scaleX = canvas.width / rect.width const scaleY = canvas.height / rect.height return { x: x * scaleX, y: y * scaleY } } const startDrawing = (e: React.MouseEvent | React.TouchEvent) => { e.preventDefault() const point = getCoordinates(e) if (!point) return // Clear placeholder text on first draw if (!hasDrawn) { const canvas = canvasRef.current const ctx = canvas?.getContext("2d") if (canvas && ctx) { ctx.fillStyle = "#ffffff" ctx.fillRect(0, 0, canvas.width, canvas.height) } } setIsDrawing(true) setLastPoint(point) } const draw = (e: React.MouseEvent | React.TouchEvent) => { e.preventDefault() if (!isDrawing) return const canvas = canvasRef.current const ctx = canvas?.getContext("2d") if (!canvas || !ctx) return const point = getCoordinates(e) if (!point || !lastPoint) return // Draw line ctx.strokeStyle = "#000000" ctx.lineWidth = 2 ctx.lineCap = "round" ctx.lineJoin = "round" ctx.beginPath() ctx.moveTo(lastPoint.x, lastPoint.y) ctx.lineTo(point.x, point.y) ctx.stroke() setLastPoint(point) setHasDrawn(true) } const stopDrawing = () => { setIsDrawing(false) setLastPoint(null) } const hasEnoughInk = (): boolean => { const canvas = canvasRef.current if (!canvas) return false const ctx = canvas.getContext("2d") if (!ctx) return false const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height) const pixels = imageData.data let nonWhitePixels = 0 // Sample every 4th pixel for performance (checking alpha channel and RGB) for (let i = 0; i < pixels.length; i += 16) { const r = pixels[i] const g = pixels[i + 1] const b = pixels[i + 2] const a = pixels[i + 3] // Check if pixel is not white (allowing for slight variations) if (a > 0 && (r < 250 || g < 250 || b < 250)) { nonWhitePixels++ } } // Require at least 50 non-white pixels (when sampling every 4th) return nonWhitePixels >= 50 } const handleAccept = () => { const canvas = canvasRef.current if (!canvas || !props.imageAcquirer) { alert(props.T("Signature upload is not supported")) return } if (!hasEnoughInk()) { alert(props.T("Please draw a signature before accepting")) return } setIsUploading(true) const base64 = canvas.toDataURL("image/png") props.imageAcquirer.addImageFromBase64( base64, (image: Image) => { setIsUploading(false) props.onSignatureChange?.(image) }, (err: any) => { setIsUploading(false) console.error("Error uploading signature", err) alert(`${props.T("Error uploading signature")}: ${err.message || err.code || err}`) }, "image/png" ) } const handleClear = () => { if (props.signature) { // Clear existing signature props.onSignatureChange?.(null) } else { // Clear canvas const canvas = canvasRef.current if (!canvas) return const ctx = canvas.getContext("2d") if (!ctx) return // Redraw white background ctx.fillStyle = "#ffffff" ctx.fillRect(0, 0, canvas.width, canvas.height) // Redraw placeholder text ctx.fillStyle = "#999999" ctx.font = "18px sans-serif" ctx.textAlign = "center" ctx.textBaseline = "middle" ctx.fillText(props.T("Draw your signature here"), canvas.width / 2, canvas.height / 2) setHasDrawn(false) } } const handleClickImage = () => { setModalOpen(true) } const renderModal = () => { if (!modalOpen || !props.signature) { return null } const onRemove = props.onSignatureChange ? () => { setModalOpen(false) props.onSignatureChange?.(null) } : undefined return ( setModalOpen(false)} /> ) } // If signature already exists, show it if (props.signature) { return (
{renderModal()}
{props.onSignatureChange ? ( ) : null}
) } // Show canvas for drawing if (!props.imageAcquirer) { return
{props.T("Signature capture is not available")}
} return (
{hasDrawn ? ( ) : null}
) }