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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* AnyCoder - AI Code Generator
|
| 3 |
+
* Main application logic for browser-based code generation using Transformers.js
|
| 4 |
+
*/
|
| 5 |
+
|
| 6 |
+
// DOM Elements
|
| 7 |
+
const promptInput = document.getElementById('prompt');
|
| 8 |
+
const languageSelect = document.getElementById('language');
|
| 9 |
+
const generateBtn = document.getElementById('generate-btn');
|
| 10 |
+
const loadingSection = document.getElementById('loading-section');
|
| 11 |
+
const progressBar = document.getElementById('progress-bar');
|
| 12 |
+
const loadingText = document.getElementById('loading-text');
|
| 13 |
+
const errorSection = document.getElementById('error-section');
|
| 14 |
+
const errorText = document.getElementById('error-text');
|
| 15 |
+
const outputSection = document.getElementById('output-section');
|
| 16 |
+
const generatedCodeElement = document.getElementById('generated-code');
|
| 17 |
+
const copyBtn = document.getElementById('copy-btn');
|
| 18 |
+
|
| 19 |
+
// Application state
|
| 20 |
+
let isModelLoaded = false;
|
| 21 |
+
let isGenerating = false;
|
| 22 |
+
let worker = null;
|
| 23 |
+
|
| 24 |
+
// Initialize the application
|
| 25 |
+
function init() {
|
| 26 |
+
// Create and setup Web Worker
|
| 27 |
+
worker = new Worker('worker.js', { type: 'module' });
|
| 28 |
+
|
| 29 |
+
// Listen for messages from worker
|
| 30 |
+
worker.onmessage = handleWorkerMessage;
|
| 31 |
+
|
| 32 |
+
// Setup event listeners
|
| 33 |
+
generateBtn.addEventListener('click', handleGenerate);
|
| 34 |
+
copyBtn.addEventListener('click', handleCopy);
|
| 35 |
+
promptInput.addEventListener('keydown', (e) => {
|
| 36 |
+
if (e.key === 'Enter' && e.ctrlKey) {
|
| 37 |
+
handleGenerate();
|
| 38 |
+
}
|
| 39 |
+
});
|
| 40 |
+
|
| 41 |
+
// Load model on page load
|
| 42 |
+
loadModel();
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
// Handle messages from Web Worker
|
| 46 |
+
function handleWorkerMessage(event) {
|
| 47 |
+
const { type, data } = event.data;
|
| 48 |
+
|
| 49 |
+
switch (type) {
|
| 50 |
+
case 'progress':
|
| 51 |
+
updateProgress(data);
|
| 52 |
+
break;
|
| 53 |
+
case 'modelLoaded':
|
| 54 |
+
onModelLoaded();
|
| 55 |
+
break;
|
| 56 |
+
case 'generationComplete':
|
| 57 |
+
onGenerationComplete(data);
|
| 58 |
+
break;
|
| 59 |
+
case 'error':
|
| 60 |
+
onError(data);
|
| 61 |
+
break;
|
| 62 |
+
default:
|
| 63 |
+
console.warn('Unknown message type from worker:', type);
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
// Load the model
|
| 68 |
+
function loadModel() {
|
| 69 |
+
loadingSection.style.display = 'block';
|
| 70 |
+
loadingText.textContent = 'Initializing model...';
|
| 71 |
+
|
| 72 |
+
// Send load command to worker
|
| 73 |
+
worker.postMessage({ type: 'loadModel' });
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
// Update progress bar
|
| 77 |
+
function updateProgress(progress) {
|
| 78 |
+
const percent = Math.round(progress * 100);
|
| 79 |
+
progressBar.style.width = `${percent}%`;
|
| 80 |
+
loadingText.textContent = `Loading model... ${percent}%`;
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
// Called when model is loaded
|
| 84 |
+
function onModelLoaded() {
|
| 85 |
+
isModelLoaded = true;
|
| 86 |
+
loadingSection.style.display = 'none';
|
| 87 |
+
progressBar.style.width = '0%';
|
| 88 |
+
generateBtn.disabled = false;
|
| 89 |
+
console.log('Model loaded successfully');
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
// Handle generate button click
|
| 93 |
+
async function handleGenerate() {
|
| 94 |
+
const prompt = promptInput.value.trim();
|
| 95 |
+
|
| 96 |
+
if (!prompt) {
|
| 97 |
+
showError('Please enter a description of what you want to generate.');
|
| 98 |
+
return;
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
if (!isModelLoaded) {
|
| 102 |
+
showError('Model is still loading. Please wait...');
|
| 103 |
+
return;
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
if (isGenerating) {
|
| 107 |
+
return;
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
// Clear previous errors and output
|
| 111 |
+
hideError();
|
| 112 |
+
outputSection.style.display = 'none';
|
| 113 |
+
|
| 114 |
+
// Update UI state
|
| 115 |
+
isGenerating = true;
|
| 116 |
+
generateBtn.disabled = true;
|
| 117 |
+
generateBtn.querySelector('.btn-text').textContent = 'Generating...';
|
| 118 |
+
generateBtn.querySelector('.btn-spinner').style.display = 'block';
|
| 119 |
+
|
| 120 |
+
// Prepare the prompt with language context
|
| 121 |
+
const language = languageSelect.value;
|
| 122 |
+
const enhancedPrompt = `Generate ${language} code: ${prompt}\n\n\`\`\`${language}\n`;
|
| 123 |
+
|
| 124 |
+
// Send generation request to worker
|
| 125 |
+
worker.postMessage({
|
| 126 |
+
type: 'generate',
|
| 127 |
+
data: { prompt: enhancedPrompt, language }
|
| 128 |
+
});
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
// Called when generation is complete
|
| 132 |
+
function onGenerationComplete(result) {
|
| 133 |
+
const { generatedText, language } = result;
|
| 134 |
+
|
| 135 |
+
// Extract code between code fences if present
|
| 136 |
+
let code = generatedText;
|
| 137 |
+
const codeFenceMatch = generatedText.match(/```(?:\w+)?\n([\s\S]*?)```/);
|
| 138 |
+
if (codeFenceMatch) {
|
| 139 |
+
code = codeFenceMatch[1];
|
| 140 |
+
} else {
|
| 141 |
+
// If no code fences, try to extract code after the prompt
|
| 142 |
+
const promptEnd = `Generate ${language} code:`;
|
| 143 |
+
const promptIndex = generatedText.indexOf(promptEnd);
|
| 144 |
+
if (promptIndex !== -1) {
|
| 145 |
+
code = generatedText.substring(promptIndex + promptEnd.length).trim();
|
| 146 |
+
// Remove any trailing text after code
|
| 147 |
+
const lines = code.split('\n');
|
| 148 |
+
const codeLines = [];
|
| 149 |
+
for (let line of lines) {
|
| 150 |
+
if (line.trim().startsWith('//') || line.trim().startsWith('#') || line.trim().startsWith('--')) {
|
| 151 |
+
codeLines.push(line);
|
| 152 |
+
} else if (line.trim() && !line.includes('Here is') && !line.includes('This code')) {
|
| 153 |
+
codeLines.push(line);
|
| 154 |
+
} else if (line.trim() === '') {
|
| 155 |
+
codeLines.push(line);
|
| 156 |
+
} else {
|
| 157 |
+
break;
|
| 158 |
+
}
|
| 159 |
+
}
|
| 160 |
+
code = codeLines.join('\n');
|
| 161 |
+
}
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
// Clean up the code
|
| 165 |
+
code = code.trim();
|
| 166 |
+
|
| 167 |
+
// Update the UI
|
| 168 |
+
displayGeneratedCode(code, language);
|
| 169 |
+
|
| 170 |
+
// Reset UI state
|
| 171 |
+
resetUIState();
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
// Display generated code with syntax highlighting
|
| 175 |
+
function displayGeneratedCode(code, language) {
|
| 176 |
+
// Set the code content
|
| 177 |
+
generatedCodeElement.textContent = code;
|
| 178 |
+
|
| 179 |
+
// Update language class
|
| 180 |
+
generatedCodeElement.className = `language-${getPrismLanguage(language)}`;
|
| 181 |
+
|
| 182 |
+
// Highlight the code
|
| 183 |
+
Prism.highlightElement(generatedCodeElement);
|
| 184 |
+
|
| 185 |
+
// Show output section
|
| 186 |
+
outputSection.style.display = 'block';
|
| 187 |
+
|
| 188 |
+
// Scroll to output
|
| 189 |
+
outputSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
// Get Prism.js language identifier
|
| 193 |
+
function getPrismLanguage(language) {
|
| 194 |
+
const languageMap = {
|
| 195 |
+
'javascript': 'javascript',
|
| 196 |
+
'python': 'python',
|
| 197 |
+
'html': 'markup',
|
| 198 |
+
'react': 'jsx',
|
| 199 |
+
'sql': 'sql',
|
| 200 |
+
'bash': 'bash',
|
| 201 |
+
'other': 'javascript'
|
| 202 |
+
};
|
| 203 |
+
return languageMap[language] || 'javascript';
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
// Handle copy button click
|
| 207 |
+
async function handleCopy() {
|
| 208 |
+
const code = generatedCodeElement.textContent;
|
| 209 |
+
|
| 210 |
+
try {
|
| 211 |
+
await navigator.clipboard.writeText(code);
|
| 212 |
+
const originalText = copyBtn.textContent;
|
| 213 |
+
copyBtn.textContent = 'Copied!';
|
| 214 |
+
copyBtn.style.backgroundColor = 'var(--accent-success)';
|
| 215 |
+
|
| 216 |
+
setTimeout(() => {
|
| 217 |
+
copyBtn.textContent = originalText;
|
| 218 |
+
copyBtn.style.backgroundColor = '';
|
| 219 |
+
}, 2000);
|
| 220 |
+
} catch (err) {
|
| 221 |
+
console.error('Failed to copy code:', err);
|
| 222 |
+
showError('Failed to copy code to clipboard');
|
| 223 |
+
}
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
// Show error message
|
| 227 |
+
function showError(message) {
|
| 228 |
+
errorText.textContent = message;
|
| 229 |
+
errorSection.style.display = 'block';
|
| 230 |
+
|
| 231 |
+
// Auto-hide after 5 seconds
|
| 232 |
+
setTimeout(hideError, 5000);
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
// Hide error message
|
| 236 |
+
function hideError() {
|
| 237 |
+
errorSection.style.display = 'none';
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
// Reset UI state after generation
|
| 241 |
+
function resetUIState() {
|
| 242 |
+
isGenerating = false;
|
| 243 |
+
generateBtn.disabled = false;
|
| 244 |
+
generateBtn.querySelector('.btn-text').textContent = 'Generate Code';
|
| 245 |
+
generateBtn.querySelector('.btn-spinner').style.display = 'none';
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
// Handle errors from worker
|
| 249 |
+
function onError(error) {
|
| 250 |
+
console.error('Worker error:', error);
|
| 251 |
+
showError(`An error occurred: ${error.message || 'Unknown error'}`);
|
| 252 |
+
resetUIState();
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
// Initialize the app when DOM is ready
|
| 256 |
+
if (document.readyState === 'loading') {
|
| 257 |
+
document.addEventListener('DOMContentLoaded', init);
|
| 258 |
+
} else {
|
| 259 |
+
init();
|
| 260 |
+
}
|