// Description: This component handles the format conversion between different chemical notations. import { useState, useRef } from "react"; // Ensure all used icons are imported // Assuming these components are correctly implemented and styled for dark/light mode import SMILESInput from "../common/SMILESInput"; import MoleculeDepiction2D from "../depict/MoleculeDepiction2D"; import { ToolSkeleton } from "@/components/feedback/ToolSkeleton"; import { GlassErrorCard } from "@/components/feedback/GlassErrorCard"; import { EmptyState } from "@/components/feedback/EmptyState"; import { getErrorMessage } from "@/lib/error-messages"; // Assuming this service is configured correctly import convertService from "../../services/convertService"; import XYZGridResult from "./XYZGridResult"; import type { XYZBatchConversionResult } from "@/types/api"; import { AlertCircle, ArrowLeftRight, ArrowRight, Check, Clipboard, FileText, Loader2, Upload, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; // Input format options configuration const INPUT_FORMAT_OPTIONS = [ { id: "smiles", label: "SMILES" }, { id: "iupac", label: "IUPAC Name" }, { id: "selfies", label: "SELFIES" }, { id: "molsdf", label: "MOL/SDF Block" }, { id: "cdx", label: "ChemDraw CDX/CDXML" }, { id: "xyz", label: "XYZ Coordinates" }, ]; // Output format options configuration const OUTPUT_FORMAT_OPTIONS = [ { id: "smiles", label: "SMILES", method: null }, { id: "canonicalsmiles", label: "Canonical SMILES", method: "generateCanonicalSMILES", }, { id: "inchi", label: "InChI", method: "generateInChI" }, { id: "inchikey", label: "InChI Key", method: "generateInChIKey" }, { id: "cxsmiles", label: "CXSMILES", method: "generateCXSMILES" }, { id: "selfies", label: "SELFIES", method: "generateSELFIES" }, { id: "smarts", label: "SMARTS", method: "generateSMARTS" }, { id: "mol", label: "MOL Block", method: null }, { id: "sdf", label: "SDF", method: null }, ]; // Output formats reachable from XYZ input. const XYZ_OUTPUT_FORMAT_IDS = new Set(["canonicalsmiles", "inchi", "inchikey", "mol", "sdf"]); // Toolkit options configuration const TOOLKIT_OPTIONS = [ { id: "cdk", label: "CDK (Chemistry Development Kit)" }, { id: "rdkit", label: "RDKit" }, { id: "openbabel", label: "OpenBabel" }, ]; // Converter options for IUPAC const IUPAC_CONVERTER_OPTIONS = [{ id: "opsin", label: "OPSIN" }]; // Detect whether input text is SMILES, SELFIES, or IUPAC name const detectInputFormat = (text) => { const trimmed = text.trim(); if (!trimmed) return null; // SELFIES: entirely composed of [token] sequences if (/^(\[[\w@=#+\-/\\%;.,^*]+\])+$/.test(trimmed)) return "selfies"; // IUPAC: word-like name — only lowercase letters, digits, spaces, hyphens, commas, // parentheses; and no SMILES ring-closure patterns (letter immediately adjacent to digit) if ( /^[a-z0-9][a-z0-9 ,\-().]*$/.test(trimmed) && !/[a-z]\d/.test(trimmed) && !/\d[a-z]/.test(trimmed) ) { return "iupac"; } // SMILES: no whitespace, only valid SMILES characters if (!/\s/.test(trimmed) && /^[A-Za-z0-9[\]()=#@+\-/.\\%:*]+$/.test(trimmed)) return "smiles"; // Otherwise assume IUPAC name return "iupac"; }; const FormatConversionView = () => { const [input, setInput] = useState(""); const [inputFormat, setInputFormat] = useState("smiles"); const [outputFormat, setOutputFormat] = useState("canonicalsmiles"); const [toolkit, setToolkit] = useState("cdk"); const [iupacConverter, setIupacConverter] = useState("opsin"); const [result, setResult] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [copied, setCopied] = useState(false); const [autoDetected, setAutoDetected] = useState(false); // State for molecular structure display const [smilesForStructure, setSmilesForStructure] = useState(""); const [showStructure, setShowStructure] = useState(false); // State for file upload (MOL/SDF) const [uploadedFilename, setUploadedFilename] = useState(""); const fileInputRef = useRef(null); // State for CDX/CDXML file upload const [cdxFile, setCdxFile] = useState(null); const [cdxFilename, setCdxFilename] = useState(""); const cdxFileInputRef = useRef(null); // State for XYZ file upload + bond-perception parameters const [xyzFilename, setXyzFilename] = useState(""); const [xyzCharge, setXyzCharge] = useState(0); const [xyzUseHueckel, setXyzUseHueckel] = useState(false); const xyzFileInputRef = useRef(null); const [xyzBatchResult, setXyzBatchResult] = useState(null); // Helper function to ensure molblock is in proper format 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(); // V2000/V3000 molblocks have a 3-line header: name, program/timestamp, comment. // CDK-style molblocks omit the name line (start with program line), so we // prepend an empty name line. Molblocks that already include a name line // (e.g. Actelion MolfileCreator) must NOT get an extra blank line. const lines = formatted.split("\n"); const countsIdx = lines.findIndex((l) => /V[23]000/.test(l)); if (countsIdx >= 0 && countsIdx <= 2) { // Counts line found too early → name line is missing → add blank name 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 for MOL/SDF files const handleFileUpload = (e) => { const file = e.target.files[0]; if (!file) return; // Reset error and filename setError(null); setUploadedFilename(""); // Validate file extension const fileName = file.name.toLowerCase(); if (!fileName.endsWith(".mol") && !fileName.endsWith(".sdf")) { setError("Please upload a valid .mol or .sdf file."); return; } setUploadedFilename(file.name); const reader = new FileReader(); reader.onload = (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")) { setError( 'Invalid file format: The uploaded file does not appear to be a valid MOL/SDF file (missing "M END").' ); setInput(""); return; } // Check for multiple molecules const molBlockCount = (fileContent.match(/M {2}END/g) || []).length; if (molBlockCount > 1) { setError( "Multiple molecules detected in file. Please upload a file containing only one molecule." ); setInput(""); return; } // Set the content to the input setInput(fileContent); setError(null); } catch (err) { console.error("File reading error:", err); setError("Failed to process the uploaded file. Please ensure it's a valid MOL/SDF file."); setInput(""); } }; reader.onerror = () => { setError("Failed to read the uploaded file. Please ensure it's a valid text file."); setInput(""); }; reader.readAsText(file); }; // Clear uploaded MOL/SDF file const handleClearFile = () => { setUploadedFilename(""); setInput(""); if (fileInputRef.current) { fileInputRef.current.value = ""; } }; // Handle CDX/CDXML file selection const handleCdxFileUpload = (e) => { const file = e.target.files[0]; if (!file) return; setError(null); const name = file.name.toLowerCase(); if (!name.endsWith(".cdx") && !name.endsWith(".cdxml")) { setError("Please upload a valid .cdx or .cdxml file."); return; } setCdxFile(file); setCdxFilename(file.name); }; // Clear uploaded CDX file const handleClearCdxFile = () => { setCdxFile(null); setCdxFilename(""); if (cdxFileInputRef.current) { cdxFileInputRef.current.value = ""; } }; // Handle XYZ file selection — read as text and place in the input textarea. const handleXyzFileUpload = (e) => { const file = e.target.files[0]; if (!file) return; setError(null); if (!file.name.toLowerCase().endsWith(".xyz")) { setError("Please upload a valid .xyz file."); return; } setXyzFilename(file.name); const reader = new FileReader(); reader.onload = (event) => { const content = event.target.result; setInput(typeof content === "string" ? content : ""); }; reader.onerror = () => setError("Failed to read the uploaded XYZ file."); reader.readAsText(file); }; // Clear uploaded XYZ file const handleClearXyzFile = () => { setXyzFilename(""); setInput(""); setXyzBatchResult(null); if (xyzFileInputRef.current) { xyzFileInputRef.current.value = ""; } }; // When input format changes, automatically update output format if needed const handleInputFormatChange = (format) => { setInputFormat(format); setAutoDetected(false); // Clear MOL/SDF file when switching away from molsdf if (format !== "molsdf") { handleClearFile(); } // Clear CDX file when switching away from cdx if (format !== "cdx") { handleClearCdxFile(); } // Clear XYZ file when switching away from xyz if (format !== "xyz") { handleClearXyzFile(); } // Lock output format based on input type if (format === "iupac" || format === "selfies" || format === "molsdf") { setOutputFormat("smiles"); } else if (format === "cdx") { setOutputFormat("mol"); } else if (format === "xyz") { // XYZ: default to canonical SMILES; cap toolkit to rdkit/openbabel. setOutputFormat("canonicalsmiles"); if (toolkit === "cdk") setToolkit("rdkit"); } }; // Handle text input changes with auto-format detection const handleInputChange = (value) => { setInput(value); if (inputFormat === "molsdf") return; const detected = detectInputFormat(value); if (!value.trim()) { setAutoDetected(false); return; } if (detected && detected !== inputFormat) { setInputFormat(detected); setAutoDetected(true); if (detected === "iupac" || detected === "selfies") { setOutputFormat("smiles"); } else if (detected === "smiles") { setOutputFormat("canonicalsmiles"); } } }; // When output format changes, we may need to adjust toolkit availability const handleOutputFormatChange = (format) => { setOutputFormat(format); // SMARTS only supports RDKit if (format === "smarts") { setToolkit("rdkit"); } }; // Handle form submission for conversion const handleSubmit = async (e) => { e.preventDefault(); const trimmedInput = input.trim(); if (inputFormat !== "cdx" && !trimmedInput) { setError("Please enter input data."); setResult(""); return; } if (inputFormat === "cdx" && !cdxFile) { setError("Please upload a .cdx or .cdxml file."); return; } setLoading(true); setError(null); setResult(""); setSmilesForStructure(""); setShowStructure(false); try { let convertedResult; let smilesForDisplay = ""; // XYZ → SMILES / Canonical SMILES / InChI / InChIKey / MOL / SDF if (inputFormat === "xyz") { const xyzToolkit = toolkit === "cdk" ? "rdkit" : (toolkit as "rdkit" | "openbabel"); const batch = await convertService.convertXYZ(trimmedInput, { charge: xyzCharge, useHueckel: xyzUseHueckel, toolkit: xyzToolkit, }); setXyzBatchResult(batch); // Multi-frame: the grid renders everything; suppress the single-result panel. if (batch.summary.total > 1) { setResult(""); setSmilesForStructure(""); setShowStructure(false); return; } // Single-frame path: pick the chosen output and reuse the existing UX. const only = batch.structures[0]; if (!only.success) { throw new Error(only.error || "XYZ conversion failed"); } smilesForDisplay = only.canonicalsmiles; switch (outputFormat) { case "smiles": case "canonicalsmiles": convertedResult = only.canonicalsmiles; break; case "inchi": convertedResult = only.inchi; break; case "inchikey": convertedResult = only.inchikey; break; case "mol": convertedResult = only.molblock; break; case "sdf": convertedResult = batch.sdf; break; default: throw new Error(`Unsupported output format for XYZ input: ${outputFormat}.`); } } else if (inputFormat === "cdx") { // CDX/CDXML → MOL Block const molblock = await convertService.convertCDXToMol(cdxFile); convertedResult = molblock; try { smilesForDisplay = await convertService.molblockToSMILES(molblock, "rdkit"); } catch { // Structure preview is optional } } else if (inputFormat !== "smiles") { // Handle MOL/SDF to SMILES conversion if (inputFormat === "molsdf") { // Format the MOL block properly before sending const formattedMolblock = formatMolblockForBackend(trimmedInput); const smiles = await convertService.molblockToSMILES(formattedMolblock, toolkit); smilesForDisplay = smiles; // If the output is SMILES, we're done if (outputFormat === "smiles") { convertedResult = smiles; } else if (outputFormat === "mol") { // MOL Block output: generate 2D coordinates from SMILES convertedResult = await convertService.generate2DCoordinates(smiles, toolkit); } else { // Otherwise, convert SMILES to the target format const formatOption = OUTPUT_FORMAT_OPTIONS.find((option) => option.id === outputFormat); if (!formatOption || !formatOption.method) { throw new Error(`Unsupported output format: ${outputFormat}`); } const method = convertService[formatOption.method]; if (typeof method !== "function") { throw new Error(`Conversion function not available for format: ${outputFormat}`); } // Convert the SMILES to the target format convertedResult = await method(smiles, toolkit); } } else if (inputFormat !== "cdx") { // First convert IUPAC or SELFIES to SMILES const smiles = await convertService.generateSMILES( trimmedInput, inputFormat, inputFormat === "iupac" ? iupacConverter : undefined ); // Store SMILES for structure display smilesForDisplay = smiles; // If the output is SMILES, we're done if (outputFormat === "smiles") { convertedResult = smiles; } else if (outputFormat === "mol") { // MOL Block output: generate 2D coordinates from SMILES convertedResult = await convertService.generate2DCoordinates(smiles, toolkit); } else { // Otherwise, convert SMILES to the target format const formatOption = OUTPUT_FORMAT_OPTIONS.find((option) => option.id === outputFormat); if (!formatOption || !formatOption.method) { throw new Error(`Unsupported output format: ${outputFormat}`); } const method = convertService[formatOption.method]; if (typeof method !== "function") { throw new Error(`Conversion function not available for format: ${outputFormat}`); } // Convert the SMILES to the target format convertedResult = await method(smiles, toolkit); } } } else { // Direct SMILES conversion to target format // Use the input SMILES for structure display smilesForDisplay = trimmedInput; if (outputFormat === "smiles") { // Just return the input if output is also SMILES convertedResult = trimmedInput; } else if (outputFormat === "mol") { // MOL Block output: generate 2D coordinates from SMILES convertedResult = await convertService.generate2DCoordinates(trimmedInput, toolkit); } else { const formatOption = OUTPUT_FORMAT_OPTIONS.find((option) => option.id === outputFormat); if (!formatOption || !formatOption.method) { throw new Error(`Unsupported output format: ${outputFormat}`); } const method = convertService[formatOption.method]; if (typeof method !== "function") { throw new Error(`Conversion function not available for format: ${outputFormat}`); } convertedResult = await method(trimmedInput, toolkit); } } // Handle cases where conversion might return null/undefined/empty if (!convertedResult) { setError(`Conversion resulted in empty output.`); setResult(""); setSmilesForStructure(""); setShowStructure(false); } else { let finalResult = String(convertedResult); // Remove surrounding double quotes if present if (finalResult.length >= 2 && finalResult.startsWith('"') && finalResult.endsWith('"')) { finalResult = finalResult.substring(1, finalResult.length - 1); } setResult(finalResult); // Set SMILES for structure display if we have a valid SMILES if (smilesForDisplay && smilesForDisplay.trim()) { // Clean up SMILES string - remove quotes and trim let cleanedSmiles = smilesForDisplay.trim(); if (cleanedSmiles.startsWith('"') && cleanedSmiles.endsWith('"')) { cleanedSmiles = cleanedSmiles.substring(1, cleanedSmiles.length - 1); } setSmilesForStructure(cleanedSmiles); setShowStructure(true); } } } catch (err) { console.error("Conversion failed:", err); setError(getErrorMessage("convert", err)); setResult(""); } finally { setLoading(false); } }; // Handle copying the result to clipboard const handleCopyResult = () => { if (!result || !navigator.clipboard) return; navigator.clipboard .writeText(result) .then(() => { setCopied(true); setTimeout(() => setCopied(false), 2000); }) .catch((err) => { console.error("Failed to copy result:", err); setError("Failed to copy result to clipboard."); }); }; // Determine if toolkit selection should be shown based on input/output format const showToolkitSelection = (inputFormat === "smiles" || inputFormat === "molsdf" || inputFormat === "xyz") && outputFormat !== "selfies" && outputFormat !== "smarts" && inputFormat !== "cdx"; // Determine if IUPAC converter selection should be shown const showIupacConverterSelection = inputFormat === "iupac"; return (
{/* Input and Options Card */}

Format Conversion

{/* Input Format Selection */}
{autoDetected && ( Auto-detected )}
{/* IUPAC Converter Selection (conditionally shown) */} {showIupacConverterSelection && (

OPSIN is used to convert IUPAC names to SMILES

)} {/* Input Field */}
{inputFormat === "xyz" ? ( <> {xyzFilename && (
{xyzFilename} Loaded
)}

Or paste XYZ content below