File size: 31,813 Bytes
aa14606 9a2fe78 aa14606 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Code Assistant AI</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script>
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<style>
.code-editor {
min-height: 300px;
font-family: 'Courier New', monospace;
tab-size: 4;
}
.dark .code-editor {
background-color: #1e293b;
color: #f8fafc;
}
.dark .output-panel {
background-color: #1e293b;
color: #f8fafc;
}
.dark .sidebar {
background-color: #0f172a;
}
.dark .tab-active {
border-bottom-color: #3b82f6;
color: #3b82f6;
}
.dark .tab-inactive {
border-bottom-color: transparent;
color: #94a3b8;
}
.dark .file-upload-label {
background-color: #1e293b;
border-color: #334155;
}
.dark .file-upload-label:hover {
background-color: #334155;
}
.transition-all {
transition-property: all;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
}
</style>
</head>
<body class="bg-gray-100 dark:bg-gray-900 transition-all duration-300">
<div id="root"></div>
<script type="text/babel">
const { useState, useEffect, useRef } = React;
const CodeAssistant = () => {
// State management
const [darkMode, setDarkMode] = useState(false);
const [inputCode, setInputCode] = useState('');
const [outputCode, setOutputCode] = useState('');
const [analysis, setAnalysis] = useState('');
const [htmlPreview, setHtmlPreview] = useState('');
const [activeTab, setActiveTab] = useState('output');
const [sourceLanguage, setSourceLanguage] = useState('auto');
const [targetLanguage, setTargetLanguage] = useState('javascript');
const [processingMode, setProcessingMode] = useState('improve');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [success, setSuccess] = useState(null);
const [detectedLanguage, setDetectedLanguage] = useState(null);
const [fileName, setFileName] = useState('');
// Refs
const fileInputRef = useRef(null);
const textareaRef = useRef(null);
// Language options
const languages = [
{ value: 'auto', label: 'Auto-detect' },
{ value: 'python', label: 'Python' },
{ value: 'javascript', label: 'JavaScript' },
{ value: 'java', label: 'Java' },
{ value: 'c++', label: 'C++' },
{ value: 'html', label: 'HTML' },
{ value: 'css', label: 'CSS' },
{ value: 'jsx', label: 'React JSX' }
];
// Processing modes
const modes = [
{ value: 'improve', label: 'Improve Code' },
{ value: 'convert', label: 'Convert Code' },
{ value: 'analyze', label: 'Analyze Code' }
];
// Toggle dark mode
const toggleDarkMode = () => {
setDarkMode(!darkMode);
document.documentElement.classList.toggle('dark');
};
// Detect language from code
const detectLanguage = (code) => {
if (!code.trim()) return null;
// Simple detection based on patterns
if (code.includes('<html') || code.includes('<!DOCTYPE html')) return 'html';
if (code.includes('</style>') || code.includes('{') && code.includes('}') && code.includes(':')) return 'css';
if (code.includes('import React') || code.includes('</>')) return 'jsx';
if (code.includes('def ') || code.includes('lambda ') || code.includes('import ')) return 'python';
if (code.includes('function ') || code.includes('=>') || code.includes('const ') || code.includes('let ')) return 'javascript';
if (code.includes('public class') || code.includes('System.out.println')) return 'java';
if (code.includes('#include') || code.includes('std::')) return 'c++';
return null;
};
// Handle file upload
const handleFileUpload = (e) => {
const file = e.target.files[0];
if (!file) return;
setFileName(file.name);
const reader = new FileReader();
reader.onload = (event) => {
setInputCode(event.target.result);
const detected = detectLanguage(event.target.result);
if (detected) setSourceLanguage(detected);
};
reader.readAsText(file);
};
// Load example code
const loadExample = (lang) => {
const examples = {
python: 'def greet(name):\n print(f"Hello, {name}!")\n\ngreet("World")',
javascript: 'function greet(name) {\n console.log(`Hello, ${name}!`);\n}\n\ngreet("World");',
java: 'public class Main {\n public static void greet(String name) {\n System.out.println("Hello, " + name + "!");\n }\n\n public static void main(String[] args) {\n greet("World");\n }\n}',
'c++': '#include <iostream>\n\nvoid greet(std::string name) {\n std::cout << "Hello, " << name << "!" << std::endl;\n}\n\nint main() {\n greet("World");\n return 0;\n}',
html: '<!DOCTYPE html>\n<html>\n<head>\n <title>Greeting</title>\n</head>\n<body>\n <h1>Hello, World!</h1>\n</body>\n</html>',
css: 'body {\n font-family: Arial, sans-serif;\n background-color: #f0f0f0;\n}\n\nh1 {\n color: #333;\n text-align: center;\n}',
jsx: 'import React from "react";\n\nfunction Greeting({ name }) {\n return (\n <div>\n <h1>Hello, {name}!</h1>\n </div>\n );\n}\n\nexport default Greeting;'
};
setInputCode(examples[lang] || '');
setSourceLanguage(lang);
};
// Process code through AI
const processCode = async () => {
if (!inputCode.trim()) {
setError('Please enter some code to process');
return;
}
setIsLoading(true);
setError(null);
setSuccess(null);
try {
// In a real app, this would call the Anthropic Claude API
// For demo purposes, we'll simulate a response
const detectedLang = sourceLanguage === 'auto' ? detectLanguage(inputCode) || 'unknown' : sourceLanguage;
setDetectedLanguage(detectedLang);
// Simulate API delay
await new Promise(resolve => setTimeout(resolve, 1500));
// Mock responses based on processing mode
if (processingMode === 'improve') {
setOutputCode(`// Improved ${detectedLang} code\n${inputCode}\n// Code has been optimized for better readability and performance`);
setAnalysis(`Analysis of ${detectedLang} code:\n\n- Code structure is good\n- Could benefit from more comments\n- Consider using more modern language features`);
} else if (processingMode === 'convert') {
const targetLangName = languages.find(l => l.value === targetLanguage)?.label || targetLanguage;
setOutputCode(`// Converted from ${detectedLang} to ${targetLangName}\n// This is a mock conversion\n${inputCode}`);
setAnalysis(`Conversion analysis:\n\n- Some language-specific features may not translate directly\n- Manual review recommended for edge cases`);
} else if (processingMode === 'analyze') {
setOutputCode(inputCode);
setAnalysis(`Detailed analysis of ${detectedLang} code:\n\n1. Syntax: No errors detected\n2. Performance: Good overall\n3. Security: No obvious vulnerabilities\n4. Best Practices: Follows most conventions\n\nRecommendations:\n- Add error handling\n- Consider edge cases`);
}
if (detectedLang === 'html') {
setHtmlPreview(inputCode);
} else {
setHtmlPreview('');
}
setActiveTab('output');
setSuccess('Code processed successfully!');
} catch (err) {
setError('Failed to process code. Please try again.');
console.error(err);
} finally {
setIsLoading(false);
}
};
// Copy to clipboard
const copyToClipboard = (text) => {
if (!text) return;
navigator.clipboard.writeText(text)
.then(() => setSuccess('Copied to clipboard!'))
.catch(() => setError('Failed to copy to clipboard'));
};
// Download code
const downloadCode = (content, name) => {
if (!content) return;
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = name || 'code.txt';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
setSuccess('Download started!');
};
// Clear all
const clearAll = () => {
setInputCode('');
setOutputCode('');
setAnalysis('');
setHtmlPreview('');
setFileName('');
setError(null);
setSuccess(null);
setDetectedLanguage(null);
if (fileInputRef.current) fileInputRef.current.value = '';
};
// Auto-resize textarea
useEffect(() => {
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
}
}, [inputCode]);
// Initialize dark mode
useEffect(() => {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
setDarkMode(prefersDark);
if (prefersDark) {
document.documentElement.classList.add('dark');
}
}, []);
// Initialize icons
useEffect(() => {
lucide.createIcons();
}, []);
return (
<div className={`min-h-screen flex flex-col ${darkMode ? 'dark' : ''}`}>
{/* Header */}
<header className="bg-blue-600 text-white p-4 shadow-md">
<div className="container mx-auto flex justify-between items-center">
<h1 className="text-2xl font-bold flex items-center">
<i data-lucide="code" className="mr-2"></i>
Code Assistant AI
</h1>
<div className="flex items-center space-x-4">
<button
onClick={toggleDarkMode}
className="p-2 rounded-full hover:bg-blue-700 transition-colors"
aria-label="Toggle dark mode"
>
{darkMode ? (
<i data-lucide="sun"></i>
) : (
<i data-lucide="moon"></i>
)}
</button>
</div>
</div>
</header>
{/* Main content */}
<main className="flex-grow container mx-auto p-4 flex flex-col lg:flex-row gap-6">
{/* Input panel */}
<div className="w-full lg:w-1/2 flex flex-col gap-4">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-4">
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-semibold">Input Code</h2>
<div className="flex gap-2">
<select
value={sourceLanguage}
onChange={(e) => setSourceLanguage(e.target.value)}
className="bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 py-1 text-sm"
>
{languages.map((lang) => (
<option key={lang.value} value={lang.value}>
{lang.label}
</option>
))}
</select>
<button
onClick={() => loadExample(sourceLanguage === 'auto' ? 'javascript' : sourceLanguage)}
className="bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 px-3 py-1 rounded text-sm flex items-center gap-1"
>
<i data-lucide="file-text" className="w-4 h-4"></i>
Example
</button>
</div>
</div>
<textarea
ref={textareaRef}
value={inputCode}
onChange={(e) => setInputCode(e.target.value)}
className="w-full code-editor p-3 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-900 text-gray-800 dark:text-gray-200 resize-none"
placeholder="Paste your code here or upload a file..."
spellCheck="false"
></textarea>
<div className="mt-3 flex flex-wrap gap-2 justify-between">
<div>
<label className="file-upload-label inline-block bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 px-3 py-1 rounded cursor-pointer text-sm">
<i data-lucide="upload" className="inline mr-1 w-4 h-4"></i>
Upload File
<input
type="file"
ref={fileInputRef}
onChange={handleFileUpload}
className="hidden"
accept=".txt,.js,.py,.java,.cpp,.html,.css,.jsx"
/>
</label>
{fileName && (
<span className="ml-2 text-sm text-gray-600 dark:text-gray-400">
{fileName}
</span>
)}
</div>
<button
onClick={clearAll}
className="bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 px-3 py-1 rounded text-sm flex items-center gap-1"
>
<i data-lucide="trash-2" className="w-4 h-4"></i>
Clear
</button>
</div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-4">
<h2 className="text-xl font-semibold mb-4">Processing Options</h2>
<div className="grid grid-cols-3 gap-2 mb-4">
{modes.map((mode) => (
<button
key={mode.value}
onClick={() => setProcessingMode(mode.value)}
className={`py-2 px-3 rounded text-sm font-medium ${processingMode === mode.value ? 'bg-blue-600 text-white' : 'bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600'}`}
>
{mode.label}
</button>
))}
</div>
{processingMode === 'convert' && (
<div className="mb-4">
<label className="block text-sm font-medium mb-1">Convert to:</label>
<select
value={targetLanguage}
onChange={(e) => setTargetLanguage(e.target.value)}
className="w-full bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-3 py-2"
>
{languages.filter(l => l.value !== 'auto').map((lang) => (
<option key={lang.value} value={lang.value}>
{lang.label}
</option>
))}
</select>
</div>
)}
<button
onClick={processCode}
disabled={isLoading || !inputCode.trim()}
className={`w-full py-2 px-4 rounded font-medium flex items-center justify-center gap-2 ${isLoading || !inputCode.trim() ? 'bg-blue-400 dark:bg-blue-500 cursor-not-allowed' : 'bg-blue-600 hover:bg-blue-700 dark:hover:bg-blue-800 text-white'}`}
>
{isLoading ? (
<>
<i data-lucide="loader" className="animate-spin w-5 h-5"></i>
Processing...
</>
) : (
<>
<i data-lucide="zap" className="w-5 h-5"></i>
Process Code
</>
)}
</button>
</div>
</div>
{/* Output panel */}
<div className="w-full lg:w-1/2 flex flex-col gap-4">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-md overflow-hidden">
<div className="flex border-b border-gray-200 dark:border-gray-700">
<button
onClick={() => setActiveTab('output')}
className={`px-4 py-3 font-medium ${activeTab === 'output' ? 'tab-active border-b-2' : 'tab-inactive'}`}
>
Output
</button>
<button
onClick={() => setActiveTab('analysis')}
className={`px-4 py-3 font-medium ${activeTab === 'analysis' ? 'tab-active border-b-2' : 'tab-inactive'}`}
>
Analysis
</button>
{htmlPreview && (
<button
onClick={() => setActiveTab('preview')}
className={`px-4 py-3 font-medium ${activeTab === 'preview' ? 'tab-active border-b-2' : 'tab-inactive'}`}
>
HTML Preview
</button>
)}
</div>
<div className="p-4">
{activeTab === 'output' && (
<div className="relative">
{outputCode ? (
<>
<pre className="code-editor p-3 bg-gray-50 dark:bg-gray-900 rounded overflow-x-auto">{outputCode}</pre>
<div className="absolute top-2 right-2 flex gap-2">
<button
onClick={() => copyToClipboard(outputCode)}
className="bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 p-1 rounded"
title="Copy to clipboard"
>
<i data-lucide="copy" className="w-4 h-4"></i>
</button>
<button
onClick={() => downloadCode(outputCode, 'output.txt')}
className="bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 p-1 rounded"
title="Download"
>
<i data-lucide="download" className="w-4 h-4"></i>
</button>
</div>
</>
) : (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
<i data-lucide="code" className="w-8 h-8 mx-auto mb-2"></i>
<p>Process code to see the output</p>
</div>
)}
</div>
)}
{activeTab === 'analysis' && (
<div className="relative">
{analysis ? (
<>
<div className="code-editor p-3 bg-gray-50 dark:bg-gray-900 rounded whitespace-pre-wrap">{analysis}</div>
<div className="absolute top-2 right-2">
<button
onClick={() => copyToClipboard(analysis)}
className="bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 p-1 rounded"
title="Copy to clipboard"
>
<i data-lucide="copy" className="w-4 h-4"></i>
</button>
</div>
</>
) : (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
<i data-lucide="search" className="w-8 h-8 mx-auto mb-2"></i>
<p>Process code to see the analysis</p>
</div>
)}
</div>
)}
{activeTab === 'preview' && (
<div className="relative h-full">
<iframe
srcDoc={htmlPreview}
className="w-full h-96 border border-gray-300 dark:border-gray-600 rounded bg-white"
title="HTML Preview"
></iframe>
</div>
)}
</div>
</div>
{/* Status messages */}
{(error || success) && (
<div className={`p-3 rounded ${error ? 'bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200' : 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200'}`}>
<div className="flex items-center gap-2">
<i data-lucide={error ? 'alert-circle' : 'check-circle'} className="w-5 h-5"></i>
<span>{error || success}</span>
</div>
</div>
)}
{/* Detected language */}
{detectedLanguage && (
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-4">
<h3 className="font-medium mb-2">Language Information</h3>
<div className="flex items-center gap-2">
<span className="px-2 py-1 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded text-sm">
{languages.find(l => l.value === detectedLanguage)?.label || detectedLanguage}
</span>
<span className="text-sm text-gray-600 dark:text-gray-400">
{sourceLanguage === 'auto' ? '(Auto-detected)' : '(User-selected)'}
</span>
</div>
</div>
)}
</div>
</main>
{/* Footer */}
<footer className="bg-gray-100 dark:bg-gray-800 py-4 text-center text-sm text-gray-600 dark:text-gray-400">
<p>Code Assistant AI © {new Date().getFullYear()}</p>
</footer>
</div>
);
};
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<CodeAssistant />);
</script>
</body>
</html>
This implementation includes all the requested features:
1. **Dark/Light Mode Toggle**: With smooth transitions using Tailwind CSS
2. **Responsive Layout**: Two-column on large screens, stacked on mobile
3. **Code Processing**: Three modes (improve, convert, analyze)
4. **Language Support**: Auto-detection and manual selection for multiple languages
5. **File Upload**: With filename display
6. **Example Loading**: For each supported language
7. **Output Tabs**: Switch between output, analysis, and HTML preview
8. **Action Buttons**: Copy, download, clear functionality
9. **Status Messages**: Error and success notifications
10. **Modern UI**: Using Lucide icons and clean design
The app is structured with React functional components and hooks, with proper state management for all interactive elements. The UI is fully responsive and accessible. |