// Description: A reusable React component for uploading and converting MOL/SDF files to SMILES import { useState, useRef } from "react"; import convertService from "../../services/convertService"; import { AlertCircle, CheckCircle, FileText, Upload, X } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; /** * MolFileUpload Component * * A reusable component that allows users to upload MOL/SDF files and convert them to SMILES using CDK or RDKit. * * @param {Object} props * @param {Function} props.onConversionSuccess - Callback when conversion is successful, receives (smiles, molblock, filename) * @param {Function} props.onConversionError - Callback when conversion fails, receives (error) * @param {string} props.toolkit - Toolkit to use for conversion: "cdk" (default) or "rdkit" * @param {string} props.className - Additional CSS classes for the container * @param {boolean} props.showMolblock - Whether to display the MOL block content (default: false) * @param {boolean} props.allowMultipleMolecules - Whether to allow SDF files with multiple molecules (default: false) */ const MolFileUpload = ({ onConversionSuccess, onConversionError, toolkit = "cdk", className = "", showMolblock = false, allowMultipleMolecules = false, }) => { const [molblock, setMolblock] = useState(""); const [filename, setFilename] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [smiles, setSmiles] = useState(""); const fileInputRef = useRef(null); // Helper function to format molblock for backend const formatMolblockForBackend = (molblock) => { // Normalize line endings first let formatted = molblock.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); // Clean up - remove trailing spaces from each line and trim formatted = formatted .split("\n") .map((line) => line.trimEnd()) .join("\n") .trim(); // Ensure proper molblock format - starts with newline if (!formatted.startsWith("\n")) { formatted = "\n" + formatted; } // Ensure it ends with M END followed by a newline if (!formatted.endsWith("M END\n")) { if (formatted.endsWith("M END")) { formatted += "\n"; } } return formatted; }; // Handle file upload and read content const handleFileUpload = async (e) => { const file = e.target.files[0]; if (!file) return; // Reset state setError(null); setSmiles(""); setMolblock(""); setFilename(""); // Validate file extension const fileName = file.name.toLowerCase(); if (!fileName.endsWith(".mol") && !fileName.endsWith(".sdf")) { const errorMsg = "Please upload a valid .mol or .sdf file."; setError(errorMsg); if (onConversionError) onConversionError(errorMsg); return; } setFilename(file.name); setLoading(true); const reader = new FileReader(); reader.onload = async (event) => { try { let fileContent = event.target.result; // Normalize line endings and trim fileContent = fileContent.replace(/\r\n/g, "\n").replace(/\r/g, "\n").trim(); // Validate molblock format if (!fileContent.includes("M END")) { throw new Error( 'Invalid file format: The uploaded file does not appear to be a valid MOL/SDF file (missing "M END").' ); } // Check for multiple molecules if not allowed if (!allowMultipleMolecules) { const molBlockCount = (fileContent.match(/M {2}END/g) || []).length; if (molBlockCount > 1) { throw new Error( "Multiple molecules detected in file. This component only supports single molecules. Please upload a file containing only one molecule." ); } } // Handle SDF terminator - extract first molecule if (fileContent.includes("$$$$")) { fileContent = fileContent.split("$$$$")[0].trim(); } setMolblock(fileContent); // Format and convert to SMILES const formattedMolblock = formatMolblockForBackend(fileContent); const convertedSmiles = await convertService.molblockToSMILES(formattedMolblock, toolkit); // Clean up SMILES (remove quotes if present) const cleanSmiles = convertedSmiles.replace(/^"|"$/g, "").trim(); setSmiles(cleanSmiles); setError(null); // Call success callback if (onConversionSuccess) { onConversionSuccess(cleanSmiles, fileContent, file.name); } } catch (err) { console.error("File conversion error:", err); const errorMsg = err.message || "Failed to convert MOL/SDF file to SMILES."; setError(errorMsg); if (onConversionError) onConversionError(errorMsg); } finally { setLoading(false); } }; reader.onerror = () => { const errorMsg = "Failed to read the uploaded file. Please ensure it's a valid text file."; setError(errorMsg); setLoading(false); if (onConversionError) onConversionError(errorMsg); }; reader.readAsText(file); }; // Clear/reset the component const handleClear = () => { setMolblock(""); setFilename(""); setSmiles(""); setError(null); if (fileInputRef.current) { fileInputRef.current.value = ""; } }; return (
Supports .mol and .sdf file formats
{error}
Conversion Successful
SMILES:
{smiles}
MOL Block Content
{molblock}