import { useCallback, useRef, useState } from "preact/hooks"; import { encryptDataWithStoredPassword, getEncryptionPassword, } from "../helpers.ts"; interface AddIncomeModalProps { userId?: string; } export default function AddIncomeModal( { userId }: AddIncomeModalProps, ) { const formRef = useRef(null); const encryptedDataRef = useRef(null); const sourceRef = useRef(null); const amountRef = useRef(null); 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 source = sourceRef.current?.value || ""; const amount = amountRef.current?.value || ""; // Check if encryption is available and encrypt the sensitive fields if (userId && (source || amount)) { const encryptionPassword = getEncryptionPassword(userId); if (encryptionPassword) { try { const dataToEncrypt = { source: source, amount: parseFloat(amount) || 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 income data:", error); } } } }, [userId]); const handleAddClick = async () => { setLoading(true); // Encrypt data before submission await handleEncryptData(); // Get current values from the form inputs const source = sourceRef.current?.value || ""; const amount = amountRef.current?.value || ""; // Clear plaintext fields if encryption was successful if (userId && (source || amount)) { const encryptionPassword = getEncryptionPassword(userId); if (encryptionPassword && encryptedDataRef.current?.value) { if (sourceRef.current) sourceRef.current.value = ""; if (amountRef.current) amountRef.current.value = ""; } } // Submit the form using formRef setTimeout(() => { if (formRef.current) { formRef.current.submit(); } }, 100); }; return (

Add Income

Cancel
); }