import { useCallback, useRef, useState } from "preact/hooks"; import { encryptDataWithStoredPassword, getEncryptionPassword, } from "../helpers.ts"; interface AddObligationModalProps { userId?: string; } export default function AddObligationModal( { userId }: AddObligationModalProps, ) { const formRef = useRef(null); const encryptedDataRef = useRef(null); const descriptionRef = useRef(null); const amountRef = useRef(null); // Removed duplicate useState for description/amount - use refs only for form values // State only for UI feedback, not form data const [error, _setError] = useState(""); const [loading, setLoading] = useState(false); const today = new Date().toISOString().split("T")[0]; // Only encrypt on submit, not on every keystroke - prevents V8 overload const handleEncryptData = useCallback(async () => { // Get current values from the form inputs const desc = descriptionRef.current?.value || ""; const amt = amountRef.current?.value || ""; // Check if encryption is available and encrypt the sensitive fields if (userId && (desc || amt)) { const encryptionPassword = getEncryptionPassword(userId); if (encryptionPassword) { try { const dataToEncrypt = { description: desc, amount: parseFloat(amt) || 0, }; const encryptedData = await encryptDataWithStoredPassword( userId, JSON.stringify(dataToEncrypt), ); if (encryptedData && encryptedDataRef.current) { // Set encrypted data encryptedDataRef.current.value = encryptedData; } } catch (error) { console.error("Failed to encrypt obligation data:", error); } } } }, [userId]); const handleSubmit = async () => { setLoading(true); // Encrypt data before submission await handleEncryptData(); // Get current values from the form inputs const desc = descriptionRef.current?.value || ""; const amt = amountRef.current?.value || ""; // Clear plaintext fields if encryption was successful if (userId && (desc || amt)) { const encryptionPassword = getEncryptionPassword(userId); if (encryptionPassword && encryptedDataRef.current?.value) { if (descriptionRef.current) descriptionRef.current.value = ""; if (amountRef.current) amountRef.current.value = ""; } } // Submit the form using formRef setTimeout(() => { if (formRef.current) { formRef.current.submit(); } }, 100); }; return ( <>

Add Obligation

{error &&
{error}
}
Cancel
); }