// Tab switching functionality document.addEventListener("DOMContentLoaded", () => { // Initialize theme initTheme() // Tab switching const tabButtons = document.querySelectorAll(".tab-button") const tabContents = document.querySelectorAll(".tab-content") tabButtons.forEach((button) => { button.addEventListener("click", () => { // Remove active class from all buttons and hide all contents tabButtons.forEach((btn) => btn.classList.remove("active")) tabContents.forEach((content) => content.classList.add("hidden")) // Add active class to clicked button and show corresponding content button.classList.add("active") const contentId = "content-" + button.id.split("-")[1] document.getElementById(contentId).classList.remove("hidden") // Save active tab to localStorage localStorage.setItem("activeTab", button.id) }) }) // Restore active tab from localStorage const activeTab = localStorage.getItem("activeTab") if (activeTab) { document.getElementById(activeTab)?.click() } // File input handling const fileInput = document.getElementById("fileInput") const fileName = document.getElementById("fileName") fileInput.addEventListener("change", () => { if (fileInput.files.length > 0) { fileName.textContent = fileInput.files[0].name } else { fileName.textContent = "No file chosen" } }) // Copy output button const copyButton = document.getElementById("copyOutput") copyButton.addEventListener("click", () => { const output = document.getElementById("output") navigator.clipboard .writeText(output.textContent) .then(() => { showNotification("Results copied successfully!") }) .catch((err) => { console.error("Failed to copy text: ", err) showNotification("Failed to copy text: " + err.message, "error") }) }) // Translation options toggle const translateBtn = document.getElementById("translateBtn") const translationOptions = document.getElementById("translationOptions") translateBtn.addEventListener("click", () => { // Toggle translation options visibility if (translationOptions.classList.contains("hidden")) { translationOptions.classList.remove("hidden") } else { // If options are already visible, perform translation translateText() } }) // Theme toggle const themeToggle = document.getElementById("theme-toggle") themeToggle.addEventListener("click", toggleTheme) // Add download results button const outputContainer = document.querySelector(".bg-gray-100.dark\\:bg-gray-700.p-4.rounded-xl") const downloadButton = document.createElement("button") downloadButton.id = "downloadOutput" downloadButton.className = "text-sm text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 flex items-center ml-4 transition-colors duration-200" downloadButton.innerHTML = ` Download ` downloadButton.addEventListener("click", downloadResults) // Add the download button next to the copy button const resultHeader = outputContainer.querySelector(".flex.justify-between.items-center.mb-2") resultHeader.appendChild(downloadButton) // Initialize history panel initHistoryPanel() // Make sure theme toggle is properly initialized const themeToggleBtn = document.getElementById("theme-toggle") if (themeToggleBtn) { themeToggleBtn.addEventListener("click", toggleTheme) console.log("Theme toggle button initialized") } else { console.error("Theme toggle button not found") } // Initialize theme immediately initTheme() console.log("Theme initialized:", document.documentElement.classList.contains("dark") ? "dark" : "light") }) // Theme functions function initTheme() { // Check if user preference exists in localStorage const savedTheme = localStorage.getItem("theme") if (savedTheme === "dark" || (!savedTheme && window.matchMedia("(prefers-color-scheme: dark)").matches)) { // Set dark mode document.documentElement.classList.add("dark") document.getElementById("sun-icon")?.classList.remove("hidden") document.getElementById("moon-icon")?.classList.add("hidden") } else { // Set light mode document.documentElement.classList.remove("dark") document.getElementById("sun-icon")?.classList.add("hidden") document.getElementById("moon-icon")?.classList.remove("hidden") } } function toggleTheme() { // Toggle the dark class on the html element document.documentElement.classList.toggle("dark") // Update the icons const sunIcon = document.getElementById("sun-icon") const moonIcon = document.getElementById("moon-icon") if (sunIcon && moonIcon) { if (document.documentElement.classList.contains("dark")) { // Dark mode is active sunIcon.classList.remove("hidden") moonIcon.classList.add("hidden") localStorage.setItem("theme", "dark") showNotification("Dark mode activated") } else { // Light mode is active sunIcon.classList.add("hidden") moonIcon.classList.remove("hidden") localStorage.setItem("theme", "light") showNotification("Light mode activated") } } } // Show notification function function showNotification(message, type = "success") { // Create notification element const notification = document.createElement("div") // Set class based on notification type if (type === "success") { notification.className = "notification fixed top-4 right-4 bg-green-100 border-l-4 border-green-500 text-green-700 p-4 rounded shadow-md dark:bg-green-900 dark:text-green-100 dark:border-green-400" } else if (type === "error") { notification.className = "notification fixed top-4 right-4 bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded shadow-md dark:bg-red-900 dark:text-red-100 dark:border-red-400" } else if (type === "warning") { notification.className = "notification fixed top-4 right-4 bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-4 rounded shadow-md dark:bg-yellow-900 dark:text-yellow-100 dark:border-yellow-400" } else if (type === "info") { notification.className = "notification fixed top-4 right-4 bg-blue-100 border-l-4 border-blue-500 text-blue-700 p-4 rounded shadow-md dark:bg-blue-900 dark:text-blue-100 dark:border-blue-400" } notification.innerHTML = message // Add to document document.body.appendChild(notification) // Remove after 3 seconds setTimeout(() => { notification.style.opacity = "0" notification.style.transform = "translateY(-20px)" notification.style.transition = "opacity 0.5s, transform 0.5s" setTimeout(() => { notification.remove() }, 500) }, 3000) } // Show/hide loader function toggleLoader(show) { const loader = document.getElementById("loader") if (show) { loader.classList.remove("hidden") } else { loader.classList.add("hidden") } } // Download results function function downloadResults() { const output = document.getElementById("output") const content = output.textContent || output.innerText if (!content || content.trim() === "") { showNotification("No content to download", "warning") return } // Create a blob with the content const blob = new Blob([content], { type: "text/plain" }) const url = URL.createObjectURL(blob) // Create a temporary link and trigger download const a = document.createElement("a") a.href = url a.download = "ai-results-" + new Date().toISOString().slice(0, 10) + ".txt" document.body.appendChild(a) a.click() // Clean up setTimeout(() => { document.body.removeChild(a) URL.revokeObjectURL(url) }, 100) showNotification("Results downloaded successfully!") // Add to history addToHistory("Downloaded results", content.substring(0, 50) + (content.length > 50 ? "..." : "")) } // History management function initHistoryPanel() { // Create history panel const historyPanel = document.createElement("div") historyPanel.id = "historyPanel" historyPanel.className = "fixed right-0 top-0 h-full w-80 bg-white dark:bg-gray-800 shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto" // Add history header historyPanel.innerHTML = `
No history yet
` return } // Add each history item history.forEach((item, index) => { const historyItem = document.createElement("div") historyItem.className = "bg-gray-100 dark:bg-gray-700 p-3 rounded-lg" const date = new Date(item.timestamp) const formattedDate = date.toLocaleDateString() + " " + date.toLocaleTimeString() historyItem.innerHTML = `${item.details}
` historyItemsContainer.appendChild(historyItem) }) } // Format the output based on the type of result function formatOutput(data, type) { const outputElement = document.getElementById("output") outputElement.innerHTML = "" // Clear previous content // Create a container for formatted output const container = document.createElement("div") container.className = "formatted-output" switch (type) { case "translation": // Get language names const sourceLang = getLanguageName(document.getElementById("sourceLanguage").value) const targetLang = getLanguageName(document.getElementById("targetLanguage").value) // Create translation result elements const header = document.createElement("div") header.className = "result-header" header.innerHTML = `${JSON.stringify(data, null, 2)}` } outputElement.appendChild(container) } // Text-to-speech function function speakText(text, langCode) { if (!text) return // Stop any ongoing speech window.speechSynthesis.cancel() // Create utterance const utterance = new SpeechSynthesisUtterance(text) // Map language codes to BCP 47 language tags const langMap = { ar: "ar-SA", en: "en-US", fr: "fr-FR", es: "es-ES", zh: "zh-CN", } // Set language utterance.lang = langMap[langCode] || "en-US" // Get available voices const voices = window.speechSynthesis.getVoices() // Try to find a voice for the selected language const voice = voices.find((v) => v.lang.startsWith(langMap[langCode]?.split("-")[0] || "en")) if (voice) { utterance.voice = voice } // Speak window.speechSynthesis.speak(utterance) // Show notification showNotification("Playing audio...", "info") } // Helper function to get language name from code function getLanguageName(code) { const languages = { ar: "Arabic", en: "English", fr: "French", es: "Spanish", zh: "Chinese", } return languages[code] || code } // API Functions async function uploadFile(endpoint) { const fileInput = document.getElementById("fileInput") const file = fileInput.files[0] if (!file) { showNotification("Please select a file first.", "warning") return } toggleLoader(true) const formData = new FormData() formData.append("file", file) try { const response = await fetch(`https://soltane777-textgeneration.hf.space/${endpoint}`, { method: "POST", body: formData, }) if (!response.ok) { throw new Error(`Server responded with status: ${response.status}`) } const data = await response.json() formatOutput(data, endpoint) } catch (error) { console.error("Error:", error) document.getElementById("output").innerHTML = ` ` showNotification("Error processing file: " + (error.message || "Unknown error"), "error") } finally { toggleLoader(false) } } async function processText(endpoint) { // If endpoint is translate, we now handle it separately if (endpoint === "translate") { // Show translation options if they're hidden if (document.getElementById("translationOptions").classList.contains("hidden")) { document.getElementById("translationOptions").classList.remove("hidden") return } return translateText() } const text = document.getElementById("textInput").value if (!text) { showNotification("Please enter text first.", "warning") return } toggleLoader(true) const formData = new FormData() formData.append("text", text) try { const response = await fetch(`https://soltane777-textgeneration.hf.space/${endpoint}`, { method: "POST", body: formData, }) if (!response.ok) { throw new Error(`Server responded with status: ${response.status}`) } const data = await response.json() formatOutput(data, endpoint) } catch (error) { console.error("Error:", error) document.getElementById("output").innerHTML = ` ` showNotification("Error processing text: " + (error.message || "Unknown error"), "error") } finally { toggleLoader(false) } } async function translateText() { const text = document.getElementById("textInput").value const sourceLanguage = document.getElementById("sourceLanguage").value const targetLanguage = document.getElementById("targetLanguage").value if (!text) { showNotification("Please enter text to translate.", "warning") return } toggleLoader(true) const formData = new FormData() formData.append("text", text) formData.append("source_lang", sourceLanguage) formData.append("target_lang", targetLanguage) try { const response = await fetch("https://soltane777-textgeneration.hf.space/translate", { method: "POST", body: formData, }) if (!response.ok) { throw new Error(`Server responded with status: ${response.status}`) } const data = await response.json() formatOutput(data, "translation") } catch (error) { console.error("Error:", error) document.getElementById("output").innerHTML = ` ` showNotification("Error translating text: " + (error.message || "Unknown error"), "error") } finally { toggleLoader(false) } } async function askQuestion() { const context = document.getElementById("contextInput").value const question = document.getElementById("questionInput").value if (!context || !question) { showNotification("Please enter both reference text and question.", "warning") return } toggleLoader(true) try { const response = await fetch("https://soltane777-textgeneration.hf.space/qa/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ context: context, question: question }), }) if (!response.ok) { throw new Error(`Server responded with status: ${response.status}`) } const data = await response.json() formatOutput(data, "qa") } catch (error) { console.error("Error:", error) document.getElementById("output").innerHTML = ` ` showNotification("Error getting answer: " + (error.message || "Unknown error"), "error") } finally { toggleLoader(false) } } async function generateCode() { const prompt = document.getElementById("codeInput").value if (!prompt) { showNotification("Please enter a description for the code.", "warning") return } toggleLoader(true) const formData = new FormData() formData.append("prompt", prompt) try { const response = await fetch("https://soltane777-textgeneration.hf.space/generate_code/", { method: "POST", body: formData, }) if (!response.ok) { throw new Error(`Server responded with status: ${response.status}`) } const data = await response.json() formatOutput(data, "code") } catch (error) { console.error("Error:", error) document.getElementById("output").innerHTML = ` ` showNotification("Error generating code: " + (error.message || "Unknown error"), "error") } finally { toggleLoader(false) } } // Initialize speech synthesis voices if ("speechSynthesis" in window) { // Load voices speechSynthesis.onvoiceschanged = () => { speechSynthesis.getVoices() } }