Team Ai
Apppublic

Dhanesh1/codegenius-bot-your-ai-code-wizard

sourceHugging Faceupdated 11mo agoView on Hugging Face
0likes
script.js266 linesDownload Raw Back to root
1document.addEventListener('DOMContentLoaded', () => {2    const chatContainer = document.getElementById('chat-container');3    const codeForm = document.getElementById('code-form');4    const codeInput = document.getElementById('code-input');5    const languageSelect = document.getElementById('language-select');6    const copyBtn = document.getElementById('copy-btn');7    const clearBtn = document.getElementById('clear-btn');8    9    // Add a new message to the chat10    function addMessage(content, isUser = false) {11        const messageDiv = document.createElement('div');12        messageDiv.className = `flex items-start chat-message ${isUser ? 'justify-end' : ''}`;13        14        if (!isUser) {15            messageDiv.innerHTML = `16                <div class="flex-shrink-0 h-8 w-8 rounded-full bg-indigo-600 flex items-center justify-center">17                    <i data-feather="cpu" class="w-4 h-4"></i>18                </div>19                <div class="ml-3 max-w-[85%]">20                    <div class="text-sm font-medium text-indigo-400">CodeGenius</div>21                    <div class="mt-1 text-sm text-gray-300 whitespace-pre-wrap">${content}</div>22                </div>23            `;24        } else {25            messageDiv.innerHTML = `26                <div class="mr-3 max-w-[85%] text-right">27                    <div class="text-sm font-medium text-gray-400">You</div>28                    <div class="mt-1 text-sm text-gray-200 whitespace-pre-wrap">${content}</div>29                </div>30                <div class="flex-shrink-0 h-8 w-8 rounded-full bg-gray-600 flex items-center justify-center">31                    <i data-feather="user" class="w-4 h-4"></i>32                </div>33            `;34        }35        36        chatContainer.appendChild(messageDiv);37        chatContainer.scrollTop = chatContainer.scrollHeight;38        feather.replace();39    }40    41    // Show loading indicator42    function showLoading() {43        const loadingDiv = document.createElement('div');44        loadingDiv.className = 'flex items-start chat-message';45        loadingDiv.innerHTML = `46            <div class="flex-shrink-0 h-8 w-8 rounded-full bg-indigo-600 flex items-center justify-center">47                <i data-feather="cpu" class="w-4 h-4"></i>48            </div>49            <div class="ml-3">50                <div class="text-sm font-medium text-indigo-400">CodeGenius</div>51                <div class="mt-1 text-sm text-gray-300 flex items-center">52                    <span class="loading-dots">53                        <span></span>54                        <span></span>55                        <span></span>56                    </span>57                </div>58            </div>59        `;60        61        chatContainer.appendChild(loadingDiv);62        chatContainer.scrollTop = chatContainer.scrollHeight;63        return loadingDiv;64    }65    66    // Format code with syntax highlighting67    function formatCode(code, language) {68        return `<pre class="mt-2 mb-4"><code class="language-${language}">${escapeHtml(code)}</code></pre>`;69    }70    71    // Escape HTML to prevent XSS72    function escapeHtml(unsafe) {73        return unsafe74            .replace(/&/g, "&amp;")75            .replace(/</g, "&lt;")76            .replace(/>/g, "&gt;")77            .replace(/"/g, "&quot;")78            .replace(/'/g, "&#039;");79    }80    81    // Handle form submission82    codeForm.addEventListener('submit', async (e) => {83        e.preventDefault();84        const prompt = codeInput.value.trim();85        const language = languageSelect.value;86        87        if (!prompt) return;88        89        // Add user message90        addMessage(prompt, true);91        codeInput.value = '';92        93        // Show loading94        const loadingElement = showLoading();95        96        try {97            // Simulate API call to Gemini (in a real app, you would call your backend)98            // This is just a mock implementation99            setTimeout(() => {100                // Remove loading101                loadingElement.remove();102                103                // Generate more accurate response based on the prompt104                let codeResponse = '';105                let explanation = '';106                107                // Common patterns for code generation108                if (prompt.toLowerCase().includes('factorial')) {109                    explanation = 'Here\'s a function to calculate factorial:';110                    if (language === 'python') {111                        codeResponse = `def factorial(n):112    if n == 0:113        return 1114    else:115        return n * factorial(n-1)116 117# Example usage118print(factorial(5))`;119                    } else if (language === 'java') {120                        codeResponse = `public class Factorial {121    public static int factorial(int n) {122        if (n == 0) {123            return 1;124        } else {125            return n * factorial(n-1);126        }127    }128 129    public static void main(String[] args) {130        System.out.println(factorial(5));131    }132}`;133                    } else if (language === 'c') {134                        codeResponse = `#include <stdio.h>135 136int factorial(int n) {137    if (n == 0) {138        return 1;139    } else {140        return n * factorial(n-1);141    }142}143 144int main() {145    printf("%d\\n", factorial(5));146    return 0;147}`;148                    }149                } else if (prompt.toLowerCase().includes('fibonacci')) {150                    explanation = 'Here\'s a function to generate Fibonacci sequence:';151                    if (language === 'python') {152                        codeResponse = `def fibonacci(n):153    sequence = [0, 1]154    while len(sequence) < n:155        sequence.append(sequence[-1] + sequence[-2])156    return sequence[:n]157 158# Example usage159print(fibonacci(10))`;160                    } else if (language === 'java') {161                        codeResponse = `import java.util.ArrayList;162import java.util.List;163 164public class Fibonacci {165    public static List<Integer> fibonacci(int n) {166        List<Integer> sequence = new ArrayList<>();167        sequence.add(0);168        sequence.add(1);169        170        while (sequence.size() < n) {171            sequence.add(sequence.get(sequence.size()-1) + sequence.get(sequence.size()-2));172        }173        return sequence.subList(0, n);174    }175 176    public static void main(String[] args) {177        System.out.println(fibonacci(10));178    }179}`;180                    } else if (language === 'c') {181                        codeResponse = `#include <stdio.h>182 183void fibonacci(int n) {184    int a = 0, b = 1, c;185    printf("Fibonacci sequence: ");186    for (int i = 0; i < n; i++) {187        printf("%d ", a);188        c = a + b;189        a = b;190        b = c;191    }192}193 194int main() {195    fibonacci(10);196    return 0;197}`;198                    }199                } else {200                    // Fallback to more generic code for other requests201                    explanation = 'Here\'s the code you requested:';202                    if (language === 'python') {203                        codeResponse = `# ${prompt}\n# Implementation for your request\n\ndef main():\n    # Your code here\n    pass\n\nif __name__ == "__main__":\n    main()`;204                    } else if (language === 'java') {205                        codeResponse = `// ${prompt}\n// Implementation for your request\n\npublic class Main {\n    public static void main(String[] args) {\n        // Your code here\n    }\n}`;206                    } else if (language === 'c') {207                        codeResponse = `/* ${prompt} */\n/* Implementation for your request */\n\n#include <stdio.h>\n\nint main() {\n    // Your code here\n    return 0;\n}`;208                    }209                }210// Add formatted response211                addMessage(`${explanation}\n${formatCode(codeResponse, language)}`);212                213                // Load syntax highlighting214                if (window.hljs) {215                    document.querySelectorAll('pre code').forEach((block) => {216                        hljs.highlightElement(block);217                    });218                }219            }, 1500);220        } catch (error) {221            loadingElement.remove();222            addMessage(`Sorry, I encountered an error: ${error.message}`);223        }224    });225    226    // Copy code to clipboard227    copyBtn.addEventListener('click', () => {228        const lastCodeBlock = chatContainer.querySelector('pre code:last-child');229        if (lastCodeBlock) {230            navigator.clipboard.writeText(lastCodeBlock.textContent)231                .then(() => {232                    const originalText = copyBtn.innerHTML;233                    copyBtn.innerHTML = '<i data-feather="check" class="w-4 h-4 mr-2"></i> Copied!';234                    feather.replace();235                    setTimeout(() => {236                        copyBtn.innerHTML = originalText;237                        feather.replace();238                    }, 2000);239                })240                .catch(err => {241                    console.error('Failed to copy: ', err);242                });243        }244    });245    246    // Clear input247    clearBtn.addEventListener('click', () => {248        codeInput.value = '';249        codeInput.focus();250    });251    252    // Load syntax highlighting library dynamically253    if (!window.hljs) {254        const link = document.createElement('link');255        link.rel = 'stylesheet';256        link.href = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css';257        document.head.appendChild(link);258        259        const script = document.createElement('script');260        script.src = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js';261        script.onload = () => {262            hljs.highlightAll();263        };264        document.head.appendChild(script);265    }266});