Spaces:
Running
Running
| // Global Variables | |
| let chatHistory = []; | |
| let currentModel = 'Max'; | |
| let isCompactMode = false; | |
| let isConnected = true; | |
| let webSearchEnabled = false; | |
| let isGenerating = false; | |
| let currentTokenCount = 0; | |
| const maxTokens = 4096; | |
| let sidebarCollapsed = false; | |
| // Initialize | |
| document.addEventListener('DOMContentLoaded', function() { | |
| initializeApp(); | |
| setupEventListeners(); | |
| initializeSidebarToggle(); | |
| }); | |
| function initializeApp() { | |
| // Load chat history from localStorage | |
| const savedHistory = localStorage.getItem('chatHistory'); | |
| if (savedHistory) { | |
| chatHistory = JSON.parse(savedHistory); | |
| renderChatHistory(); | |
| } | |
| // Check connection status | |
| checkConnectionStatus(); | |
| // Initialize tooltips and other UI elements | |
| initializeTooltips(); | |
| } | |
| function setupEventListeners() { | |
| // Keyboard shortcuts | |
| document.addEventListener('keydown', function(e) { | |
| // Ctrl/Cmd + K for clear chat | |
| if ((e.ctrlKey || e.metaKey) && e.key === 'k') { | |
| e.preventDefault(); | |
| clearChat(); | |
| } | |
| // Escape to close modals | |
| if (e.key === 'Escape') { | |
| closeAllModals(); | |
| } | |
| // Ctrl/Cmd + / for help | |
| if ((e.ctrlKey || e.metaKey) && e.key === '/') { | |
| e.preventDefault(); | |
| showHelp(); | |
| } | |
| // Ctrl/Cmd + B to toggle sidebar | |
| if ((e.ctrlKey || e.metaKey) && e.key === 'b') { | |
| e.preventDefault(); | |
| toggleSidebar(); | |
| } | |
| }); | |
| // Auto-resize textarea | |
| const messageInput = document.getElementById('messageInput'); | |
| messageInput.addEventListener('input', function() { | |
| this.style.height = 'auto'; | |
| this.style.height = Math.min(this.scrollHeight, 120) + 'px'; | |
| }); | |
| } | |
| function initializeSidebarToggle() { | |
| console.log('Sidebar is fixed on the left side'); | |
| } | |
| function toggleSidebar() { | |
| console.log('Sidebar is fixed on the left side'); | |
| } | |
| function sendMessage() { | |
| const input = document.getElementById('messageInput'); | |
| const message = input.value.trim(); | |
| if (!message || !isConnected || isGenerating) return; | |
| // Add user message | |
| addMessage(message, 'user'); | |
| // Clear input | |
| input.value = ''; | |
| input.style.height = 'auto'; | |
| updateTokenCount(''); | |
| // Set generating state | |
| isGenerating = true; | |
| handleInput(input); | |
| // Show typing indicator | |
| showTypingIndicator(); | |
| // Simulate AI response | |
| const responseTime = currentModel === 'Max' ? 2000 : currentModel === 'Turbo' ? 1000 : 500; | |
| setTimeout(() => { | |
| isGenerating = false; | |
| hideTypingIndicator(); | |
| handleInput(input); | |
| let response = generateAIResponse(message); | |
| if (webSearchEnabled) { | |
| response += '\n\n🔍 *Web araması sonucu: `https://example.com`*'; | |
| } | |
| addMessage(response, 'ai'); | |
| }, responseTime + Math.random() * 1000); | |
| } | |
| function addMessage(content, sender) { | |
| const chatContainer = document.getElementById('chatContainer'); | |
| const timestamp = new Date().toLocaleTimeString('en-US', { | |
| hour: '2-digit', | |
| minute: '2-digit' | |
| }); | |
| const messageDiv = document.createElement('div'); | |
| messageDiv.className = `flex items-start space-x-3 message-slide-in ${sender === 'user' ? 'flex-row-reverse space-x-reverse' : ''}`; | |
| if (sender === 'user') { | |
| messageDiv.innerHTML = ` | |
| <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-blue-600 to-blue-700 flex items-center justify-center flex-shrink-0 ring-1 ring-blue-600/30 group-hover:ring-blue-500/50 transition-all duration-200"> | |
| <i data-feather="user" class="w-4.5 h-4.5 text-white"></i> | |
| </div> | |
| <div class="flex-1 max-w-4xl"> | |
| <div class="bg-gradient-to-br from-zinc-800/80 to-zinc-900/80 backdrop-blur-sm rounded-2xl p-4 border border-zinc-700/50 hover:border-zinc-600/50 transition-all duration-200 shadow-sm shadow-zinc-900/20"> | |
| <p class="text-white text-sm leading-relaxed break-words">${content}</p> | |
| </div> | |
| </div> | |
| `; | |
| } else { | |
| const processedContent = marked.parse(content); | |
| messageDiv.innerHTML = ` | |
| <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-zinc-800 to-zinc-900 flex items-center justify-center flex-shrink-0 ring-1 ring-zinc-800/50 group-hover:ring-zinc-700/50 transition-all duration-200"> | |
| <i data-feather="cpu" class="w-4.5 h-4.5 text-zinc-300"></i> | |
| </div> | |
| <div class="flex-1 max-w-4xl"> | |
| <div class="bg-gradient-to-br from-zinc-900/60 to-zinc-950/60 backdrop-blur-sm rounded-2xl p-4 border border-zinc-800/50 hover:border-zinc-700/50 transition-all duration-200 shadow-sm shadow-zinc-900/20"> | |
| <div class="markdown text-white text-sm leading-relaxed">${processedContent}</div> | |
| </div> | |
| </div> | |
| `; | |
| } | |
| chatContainer.appendChild(messageDiv); | |
| chatContainer.scrollTop = chatContainer.scrollHeight; | |
| // Re-initialize feather icons for new elements | |
| feather.replace(); | |
| // Save to history | |
| chatHistory.push({ content, sender, timestamp }); | |
| saveChatHistory(); | |
| // Update token count | |
| updateTokenCount(); | |
| } | |
| function generateAIResponse(userMessage) { | |
| const modelResponses = { | |
| 'Max': [ | |
| "I understand you're asking about: \"" + userMessage + "\". Let me help you with that. Based on my analysis, this involves several key components that we should consider carefully.", | |
| "That's an interesting question! Here's my comprehensive take on it: " + userMessage + " deserves attention because it touches on important aspects of modern technology and its applications.", | |
| "Great question! " + userMessage + " is a topic I can elaborate on in depth. From my perspective with the Max model, there are multiple approaches and nuances we should explore.", | |
| "I appreciate you bringing this up. Regarding " + userMessage + ", I think we should explore the underlying principles and practical implications thoroughly.", | |
| "This is a fascinating topic! " + userMessage + " connects to broader concepts in technology and innovation. Let me share detailed insights that might help." | |
| ], | |
| 'Turbo': [ | |
| "Quick analysis on: \"" + userMessage + "\" - Here's what I think: It involves key components worth looking at.", | |
| "Regarding " + userMessage + " - That's an interesting point worth discussing. Let me break it down for you.", | |
| "Got it! " + userMessage + " - I can help with that. Here are the main approaches to consider.", | |
| "About " + userMessage + " - Let me give you a clear perspective on this topic.", | |
| "Interesting question about " + userMessage + "! Here are some quick insights for you." | |
| ], | |
| 'Lite': [ | |
| "About: \"" + userMessage + "\" - Here's a brief overview for you.", | |
| "Regarding " + userMessage + " - Here are the key points to consider.", | |
| "Quick take on " + userMessage + " - Here's what you need to know.", | |
| "Brief analysis: " + userMessage + " - Key insights below.", | |
| "Quick reply about " + userMessage + " - Here are the essentials." | |
| ], | |
| 'Deep Research': [ | |
| "Let me conduct a deep analysis of: \"" + userMessage + "\". This query warrants comprehensive examination from multiple theoretical and practical frameworks. Based on extensive knowledge synthesis, we can identify several critical dimensions: historical context, current state-of-the-art approaches, potential future developments, and cross-disciplinary implications. The underlying mechanisms deserve careful scrutiny as they relate to broader patterns in technology evolution and cognitive science principles.", | |
| "Your inquiry about " + userMessage + " represents a sophisticated topic that benefits from deep research methodology. Drawing upon interdisciplinary knowledge domains including computer science, cognitive psychology, and systems theory, I can provide a multifaceted analysis. This exploration should consider not only surface-level implications but also second and third-order effects on ecosystem dynamics, user behavior patterns, and long-term sustainability considerations.", | |
| "Excellent research question regarding " + userMessage + ". To properly address this, we must examine it through multiple analytical lenses including technical feasibility, economic viability, social impact assessment, and ethical considerations. The complexity of this domain suggests we should also investigate precedent cases, failure modes, success patterns, and emerging trends that might influence future trajectories." | |
| ] | |
| }; | |
| const responses = modelResponses[currentModel] || modelResponses['Max']; | |
| return responses[Math.floor(Math.random() * responses.length)]; | |
| } | |
| function toggleModelDropdown() { | |
| const menu = document.getElementById('modelDropdownMenu'); | |
| const arrow = document.getElementById('modelDropdownArrow'); | |
| if (menu.classList.contains('hidden')) { | |
| menu.classList.remove('hidden'); | |
| arrow.style.transform = 'rotate(180deg)'; | |
| } else { | |
| menu.classList.add('hidden'); | |
| arrow.style.transform = 'rotate(0deg)'; | |
| } | |
| } | |
| function selectModel(model) { | |
| currentModel = model; | |
| const selectedText = document.getElementById('selectedModelText'); | |
| const indicator = document.getElementById('modelIndicator'); | |
| const modelConfig = { | |
| 'Max': { color: 'white' }, | |
| 'Turbo': { color: 'zinc-400' }, | |
| 'Lite': { color: 'zinc-500' }, | |
| 'Deep Research': { color: 'zinc-300' } | |
| }; | |
| selectedText.textContent = model; | |
| indicator.className = `w-2 h-2 bg-${modelConfig[model].color} rounded-full`; | |
| // Close dropdown | |
| document.getElementById('modelDropdownMenu').classList.add('hidden'); | |
| document.getElementById('modelDropdownArrow').style.transform = 'rotate(0deg)'; | |
| // Update model status | |
| updateModelStatus(model); | |
| } | |
| function toggleWebSearch() { | |
| webSearchEnabled = !webSearchEnabled; | |
| const toggleCircle = document.getElementById('webSearchToggleCircle'); | |
| const toggleButton = document.getElementById('webSearchToggle'); | |
| if (webSearchEnabled) { | |
| toggleCircle.style.transform = 'translateX(16px)'; | |
| toggleCircle.classList.add('bg-white'); | |
| toggleCircle.classList.remove('bg-zinc-500'); | |
| } else { | |
| toggleCircle.style.transform = 'translateX(0)'; | |
| toggleCircle.classList.remove('bg-white'); | |
| toggleCircle.classList.add('bg-zinc-500'); | |
| } | |
| } | |
| function handleInput(textarea) { | |
| // Auto resize | |
| textarea.style.height = 'auto'; | |
| textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'; | |
| // Update token count | |
| updateTokenCount(textarea.value); | |
| // Show/hide appropriate buttons | |
| const sendButton = document.getElementById('sendButton'); | |
| const stopButton = document.getElementById('stopButton'); | |
| if (isGenerating) { | |
| sendButton.classList.add('hidden'); | |
| stopButton.classList.remove('hidden'); | |
| } else { | |
| sendButton.classList.remove('hidden'); | |
| stopButton.classList.add('hidden'); | |
| } | |
| } | |
| function updateTokenCount(text) { | |
| if (!text) text = ''; | |
| // Rough estimation: average 1 token per 4 characters | |
| currentTokenCount = Math.ceil(text.length / 4); | |
| const tokenCountElement = document.getElementById('tokenCount'); | |
| const progressBar = document.getElementById('tokenProgressBar'); | |
| tokenCountElement.textContent = `${currentTokenCount} / ${maxTokens} tokens`; | |
| const percentage = Math.min((currentTokenCount / maxTokens) * 100, 100); | |
| progressBar.style.width = percentage + '%'; | |
| // Change color based on percentage | |
| if (percentage > 80) { | |
| progressBar.className = 'absolute top-0 left-0 h-full bg-gradient-to-r from-red-500 to-orange-500 rounded-full transition-all duration-300'; | |
| } else if (percentage > 60) { | |
| progressBar.className = 'absolute top-0 left-0 h-full bg-gradient-to-r from-yellow-500 to-orange-500 rounded-full transition-all duration-300'; | |
| } else { | |
| progressBar.className = 'absolute top-0 left-0 h-full bg-gradient-to-r from-white to-zinc-400 rounded-full transition-all duration-300'; | |
| } | |
| } | |
| function attachFile() { | |
| const input = document.createElement('input'); | |
| input.type = 'file'; | |
| input.onchange = e => { | |
| const file = e.target.files[0]; | |
| if (file) { | |
| addMessage(`📎 ${file.name} eklendi`, 'user'); | |
| // Handle file upload logic here | |
| } | |
| }; | |
| input.click(); | |
| } | |
| function showVoiceInput() { | |
| alert('Voice input coming soon!'); | |
| } | |
| function stopGeneration() { | |
| isGenerating = false; | |
| hideTypingIndicator(); | |
| handleInput(document.getElementById('messageInput')); | |
| } | |
| function showSettings() { | |
| alert('Settings page coming soon!'); | |
| } | |
| function updateModelStatus(model) { | |
| const responseTimes = { | |
| 'Max': '~1.2s', | |
| 'Turbo': '~0.8s', | |
| 'Lite': '~0.5s', | |
| 'Deep Research': '~2.1s' | |
| }; | |
| const responseElements = document.querySelectorAll('.text-green-400'); | |
| responseElements.forEach(el => { | |
| if (el.textContent.includes('~')) { | |
| el.textContent = responseTimes[model]; | |
| } | |
| }); | |
| } | |
| function handleKeyPress(event) { | |
| if (event.key === 'Enter' && !event.shiftKey) { | |
| event.preventDefault(); | |
| sendMessage(); | |
| } | |
| } | |
| function autoResize(textarea) { | |
| textarea.style.height = 'auto'; | |
| textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'; | |
| } | |
| function showTypingIndicator() { | |
| const typingIndicator = document.getElementById('typingIndicator'); | |
| const chatContainer = document.getElementById('chatContainer'); | |
| // Remove any existing typing indicator | |
| if (typingIndicator.parentNode === chatContainer) { | |
| typingIndicator.remove(); | |
| } | |
| // Add the typing indicator at the end of chat container | |
| chatContainer.appendChild(typingIndicator); | |
| typingIndicator.classList.remove('hidden'); | |
| typingIndicator.classList.add('message-slide-in'); | |
| // Scroll to bottom to show the indicator | |
| chatContainer.scrollTop = chatContainer.scrollHeight; | |
| // Re-initialize feather icons for the typing indicator | |
| feather.replace(); | |
| } | |
| function hideTypingIndicator() { | |
| const typingIndicator = document.getElementById('typingIndicator'); | |
| typingIndicator.classList.add('hidden'); | |
| // Remove the typing indicator from DOM when hidden | |
| if (typingIndicator.parentNode) { | |
| typingIndicator.remove(); | |
| } | |
| } | |
| function toggleChatMode() { | |
| isCompactMode = !isCompactMode; | |
| const chatContainer = document.getElementById('chatContainer'); | |
| const messages = chatContainer.querySelectorAll('.flex'); | |
| if (isCompactMode) { | |
| chatContainer.classList.add('compact'); | |
| messages.forEach(msg => { | |
| msg.style.marginBottom = '0.5rem'; | |
| }); | |
| } else { | |
| chatContainer.classList.remove('compact'); | |
| messages.forEach(msg => { | |
| msg.style.marginBottom = '1rem'; | |
| }); | |
| } | |
| localStorage.setItem('chatMode', isCompactMode ? 'compact' : 'spacious'); | |
| } | |
| function clearChat() { | |
| if (confirm('Are you sure you want to clear the entire chat history?')) { | |
| const chatContainer = document.getElementById('chatContainer'); | |
| chatContainer.innerHTML = ` | |
| <div class="flex items-start gap-3 message-slide-in group"> | |
| <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-zinc-800 to-zinc-900 flex items-center justify-center flex-shrink-0 ring-1 ring-zinc-800/50 group-hover:ring-zinc-700/50 transition-all duration-200"> | |
| <i data-feather="cpu" class="w-4.5 h-4.5 text-zinc-300"></i> | |
| </div> | |
| <div class="flex-1 max-w-4xl"> | |
| <div class="bg-gradient-to-br from-zinc-900/60 to-zinc-950/60 backdrop-blur-sm rounded-2xl p-4 border border-zinc-800/50 hover:border-zinc-700/50 transition-all duration-200 shadow-sm shadow-zinc-900/20"> | |
| <p class="text-white text-sm leading-relaxed">Hello!</p> | |
| <p class="text-zinc-400 text-sm mt-2 leading-relaxed">How can I help you today?</p> | |
| </div> | |
| </div> | |
| </div> | |
| `; | |
| chatHistory = []; | |
| saveChatHistory(); | |
| feather.replace(); | |
| } | |
| } | |
| function exportChat() { | |
| const chatText = chatHistory.map(msg => | |
| `[${msg.timestamp}] ${msg.sender === 'user' ? 'You' : 'AI'}: ${msg.content}` | |
| ).join('\n\n'); | |
| const blob = new Blob([chatText], { type: 'text/plain' }); | |
| const url = window.URL.createObjectURL(blob); | |
| const a = document.createElement('a'); | |
| a.href = url; | |
| a.download = `neural-nexus-chat-${new Date().toISOString().split('T')[0]}.txt`; | |
| a.click(); | |
| window.URL.revokeObjectURL(url); | |
| } | |
| function saveChatHistory() { | |
| localStorage.setItem('chatHistory', JSON.stringify(chatHistory)); | |
| } | |
| function renderChatHistory() { | |
| chatHistory.forEach(msg => { | |
| addMessage(msg.content, msg.sender); | |
| }); | |
| } | |
| function updateTokenCount() { | |
| const tokens = chatHistory.reduce((total, msg) => | |
| total + msg.content.split(' ').length, 0 | |
| ); | |
| const percentage = Math.min((tokens / 10000) * 100, 100); | |
| const progressBar = document.querySelector('.bg-gradient-to-r'); | |
| if (progressBar) { | |
| progressBar.style.width = percentage + '%'; | |
| } | |
| const tokenText = document.querySelector('.text-xs.text-zinc-500'); | |
| if (tokenText) { | |
| tokenText.textContent = `${tokens.toLocaleString()} / 10,000 tokens`; | |
| } | |
| } | |
| function checkConnectionStatus() { | |
| // Simulate connection check | |
| fetch('https://api.openai.com/v1/models') | |
| .then(() => { | |
| isConnected = true; | |
| updateConnectionStatus(true); | |
| }) | |
| .catch(() => { | |
| isConnected = false; | |
| updateConnectionStatus(false); | |
| }); | |
| } | |
| function updateConnectionStatus(connected) { | |
| const statusElements = document.querySelectorAll('[data-connection-status]'); | |
| statusElements.forEach(el => { | |
| el.textContent = connected ? 'Online' : 'Offline'; | |
| el.className = connected ? 'text-green-400' : 'text-red-400'; | |
| }); | |
| } | |
| function initializeTooltips() { | |
| // Add hover tooltips for icons | |
| const tooltipElements = document.querySelectorAll('[data-tooltip]'); | |
| tooltipElements.forEach(el => { | |
| el.addEventListener('mouseenter', function(e) { | |
| const tooltip = document.createElement('div'); | |
| tooltip.className = 'absolute bg-zinc-800 text-white text-xs rounded px-2 py-1 z-50'; | |
| tooltip.textContent = this.dataset.tooltip; | |
| tooltip.style.top = (e.clientY - 30) + 'px'; | |
| tooltip.style.left = e.clientX + 'px'; | |
| document.body.appendChild(tooltip); | |
| this.addEventListener('mouseleave', function() { | |
| tooltip.remove(); | |
| }, { once: true }); | |
| }); | |
| }); | |
| } | |
| function closeAllModals() { | |
| // Close any open modals or dropdowns | |
| const modals = document.querySelectorAll('.modal'); | |
| modals.forEach(modal => modal.classList.add('hidden')); | |
| } | |
| function showHelp() { | |
| const helpContent = ` | |
| Available Commands: | |
| /help - Show this help message | |
| /clear - Clear chat history | |
| /export - Export chat as text file | |
| /compact - Toggle compact mode | |
| Keyboard Shortcuts: | |
| Ctrl+K - Clear chat | |
| Ctrl+/ - Show help | |
| Tab - Auto-complete | |
| `; | |
| addMessage(helpContent, 'ai'); | |
| } | |
| // Simulate real-time updates | |
| setInterval(() => { | |
| // Update random metrics | |
| const responseTime = (0.5 + Math.random() * 0.8).toFixed(1); | |
| const responseElements = document.querySelectorAll('.text-green-400'); | |
| responseElements.forEach(el => { | |
| if (el.textContent.includes('~')) { | |
| el.textContent = `~${responseTime}s`; | |
| } | |
| }); | |
| }, 5000); |