import { useState, useEffect, useRef } from "react"; import { AlertCircle, Check, ClipboardCopy, Info, Pencil, RefreshCw, X } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { useKetcherEditor } from "@/hooks/useKetcherEditor"; // Inject fadeIn keyframe animation (idempotent — safe with HMR) const FADE_IN_STYLE_ID = "structuredraw-fadein"; if (typeof document !== "undefined" && !document.getElementById(FADE_IN_STYLE_ID)) { const styleSheet = document.createElement("style"); styleSheet.id = FADE_IN_STYLE_ID; styleSheet.textContent = ` @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } .animate-fadeIn { animation: fadeIn 0.5s ease-out forwards; }`; document.head.appendChild(styleSheet); } const StructureDrawView = () => { const [smiles, setSmiles] = useState(""); const [inputSmiles, setInputSmiles] = useState(""); const [copySuccess, setCopySuccess] = useState(false); const [showCopyModal, setShowCopyModal] = useState(false); const [copyModalText, setCopyModalText] = useState(""); const [error, setError] = useState(null); const [isLoading, setIsLoading] = useState(false); const copyTextRef = useRef(null); const { ketcherFrame, isEditorReady, executeCommand, resetEditor } = useKetcherEditor(); // Examples of common molecules const examples = [ { name: "Ethanol", value: "CCO", description: "Alcohol" }, { name: "Aspirin", value: "CC(=O)OC1=CC=CC=C1C(=O)O", description: "Pain reliever", }, { name: "Caffeine", value: "CN1C=NC2=C1C(=O)N(C)C(=O)N2C", description: "Stimulant", }, { name: "Ibuprofen", value: "CC(C)CC1=CC=C(C=C1)C(C)C(=O)O", description: "Anti-inflammatory", }, ]; // Reset error state when input changes useEffect(() => { if (error) setError(null); }, [inputSmiles, error]); // Auto-select text in copy modal when it appears useEffect(() => { if (showCopyModal && copyTextRef.current) { copyTextRef.current.select(); } }, [showCopyModal]); // Enhanced copyToClipboard function with multiple fallback methods const copyToClipboard = async (text = null) => { const textToCopy = text || smiles; if (!textToCopy) { setError("No SMILES to copy. Generate SMILES first."); return; } // Try multiple clipboard copy methods in sequence try { // Method 1: Use the Clipboard API (modern browsers) if (navigator.clipboard && navigator.clipboard.writeText) { await navigator.clipboard.writeText(textToCopy); setCopySuccess(true); setTimeout(() => setCopySuccess(false), 2000); return; } // Method 2: Use execCommand (older browsers) const textArea = document.createElement("textarea"); textArea.value = textToCopy; // Make the textarea out of viewport textArea.style.position = "fixed"; textArea.style.left = "-999999px"; textArea.style.top = "-999999px"; document.body.appendChild(textArea); // Select and copy textArea.focus(); textArea.select(); const successful = document.execCommand("copy"); document.body.removeChild(textArea); if (successful) { setCopySuccess(true); setTimeout(() => setCopySuccess(false), 2000); return; } else { throw new Error("execCommand copy failed"); } } catch (err) { console.error("Failed to copy text:", err); // Method 3: Show a modal with text to copy manually setCopyModalText(textToCopy); setShowCopyModal(true); } }; // Load SMILES into Ketcher const loadSmiles = async () => { if (!inputSmiles.trim()) { setError("Please enter a SMILES string"); return; } if (!isEditorReady) { setError("Editor not ready. Please try again in a moment."); return; } setIsLoading(true); setError(null); try { // Use the command execution function await executeCommand("setMolecule", [inputSmiles]); setSmiles(inputSmiles); } catch (err) { console.error("Failed to load SMILES:", err); setError("Invalid SMILES string or error loading structure. Please check your input."); } finally { setIsLoading(false); } }; // Get SMILES from Ketcher const getSmiles = async () => { if (!isEditorReady) { setError("Editor not ready. Please try again in a moment."); return ""; } setIsLoading(true); setError(null); try { // Use the command execution function const newSmiles = await executeCommand("getSmiles"); if (!newSmiles || newSmiles === "") { setError("No structure drawn. Please draw a molecule first."); setIsLoading(false); return ""; } setSmiles(newSmiles); return newSmiles; } catch (err) { console.error("Failed to generate SMILES:", err); setError("Could not generate SMILES from the current structure"); } finally { setIsLoading(false); } return ""; }; // Clear the editor const clearEditor = async () => { if (!isEditorReady) { console.warn("Editor not ready for clearing"); return; } try { // Use the command execution function await executeCommand("setMolecule", [""]); setSmiles(""); } catch (err) { console.error("Failed to clear editor:", err); setError("Failed to clear the editor"); } }; const handleUseExample = (exampleValue) => { setInputSmiles(exampleValue); }; // Function to retry initialization const handleRetryInit = () => { resetEditor(); setError(null); }; return (
Automatic copying failed. Please select and copy this text manually:
Quick Examples:
Structure as SMILES:
This structure editor allows you to draw chemical structures and generate their SMILES notation.
{error}