-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
847 lines (732 loc) · 26.3 KB
/
Copy pathapp.js
File metadata and controls
847 lines (732 loc) · 26.3 KB
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
/* ========================================
EXPLAIN MY CODE — App Logic
Groq API Integration (Free & Fast!)
======================================== */
// ============ CONFIG ============
const GROQ_API_URL = 'https://api.groq.com/openai/v1/chat/completions';
/**
* Using Llama 3.3 70B via Groq for high performance and speed.
* This model is excellent for coding explanations and logic reasoning.
*/
const GROQ_MODEL = 'llama-3.3-70b-versatile';
// ============ DOM ELEMENTS ============
const elements = {
codeInput: document.getElementById('code-input'),
btnExplain: document.getElementById('btn-explain'),
btnClear: document.getElementById('btn-clear'),
btnCopy: document.getElementById('btn-copy'),
btnDownload: document.getElementById('btn-download'),
outputSection: document.getElementById('output-section'),
outputContent: document.getElementById('output-content'),
outputTitle: document.getElementById('output-title'),
charCount: document.getElementById('char-count'),
wordCount: document.getElementById('word-count'),
languageSelect: document.getElementById('language-select'),
inputTitle: document.getElementById('input-title'),
modeDescText: document.getElementById('mode-desc-text'),
// Modal
apiKeyModal: document.getElementById('api-key-modal'),
apiKeyInput: document.getElementById('api-key-input'),
btnSaveKey: document.getElementById('btn-save-key'),
// Tabs
modeTabs: document.querySelectorAll('.mode-tab'),
exampleChips: document.querySelectorAll('.example-chip'),
btnResetApi: document.getElementById('btn-reset-api'),
};
// ============ STATE ============
// 'currentMode' holds the identifier of the active tab (e.g., 'explain', 'eli5', 'error').
let currentMode = 'explain';
// 'isLoading' is a boolean flag to track if an API request is currently in progress.
let isLoading = false;
// 'apiKey' stores the user's Groq API key retrieved from local storage.
let apiKey = '';
try {
apiKey = localStorage.getItem('groq_api_key') || '';
} catch (e) {
console.error('LocalStorage access denied:', e);
}
// ============ MODE CONFIGS ============
const modeConfigs = {
explain: {
title: '📋 Paste Your Code',
description: 'Paste your code and get a clear, beginner-friendly explanation.',
outputTitle: '✨ Explanation',
prompt: (code, lang) => `You are a friendly coding teacher. Explain the following ${lang} code in a clear, beginner-friendly way.
Use simple language that a beginner programmer can understand.
Structure your explanation with:
- A brief summary of what the code does
- How it works step-by-step
- Any important things to note
Use markdown formatting. Use **bold** for important terms and \`code\` for code references.
Code:
\`\`\`${lang}
${code}
\`\`\``
},
eli5: {
title: '📋 Paste Your Code',
description: '🍭 Get a super simple explanation — like you\'re explaining to a 5-year-old!',
outputTitle: '👶 ELI5 Explanation',
prompt: (code, lang) => `You are explaining code to a complete beginner who has never programmed before.
Explain this ${lang} code like you're talking to a 5-year-old child.
Use:
- Simple everyday analogies (like recipes, toys, building blocks)
- Very short sentences
- Fun emojis to make it engaging
- No technical jargon at all
- Compare programming concepts to real-world things kids understand
Use markdown formatting.
Code:
\`\`\`${lang}
${code}
\`\`\``
},
'line-by-line': {
title: '📋 Paste Your Code',
description: '📝 Every single line will be explained individually.',
outputTitle: '📝 Line-by-Line Breakdown',
prompt: (code, lang) => `You are a patient coding teacher. Break down this ${lang} code LINE BY LINE.
For each line:
1. Show the original line of code in a code block
2. Below it, explain what that line does in simple language
3. If it's important, mention WHY it's needed
Format like this for each line:
### Line X
\`\`\`
<the actual code line>
\`\`\`
**Explanation:** <what this line does>
Be thorough but keep explanations beginner-friendly. Use markdown formatting.
Code:
\`\`\`${lang}
${code}
\`\`\``
},
concepts: {
title: '📋 Paste Your Code',
description: '🔑 Highlights key concepts like loops, functions, and variables.',
outputTitle: '🔑 Key Concepts',
prompt: (code, lang) => `You are a coding teacher. Analyze this ${lang} code and identify ALL key programming concepts used.
For each concept found, explain it under a clear heading. Categorize them like:
### 🔄 Loops
Explain any loops found and how they work here.
### ⚡ Functions
Explain any functions and their purpose.
### 📦 Variables
List and explain the variables used.
### 🔀 Conditionals
Explain any if/else or switch statements.
### 📚 Data Structures
Explain any arrays, objects, lists, etc.
### 🧩 Other Concepts
Any other concepts (classes, imports, error handling, etc.)
Only include categories that are actually present in the code.
For each concept, explain it in beginner-friendly language and show the relevant code snippet.
Use markdown formatting with **bold** for terms and \`code\` for references.
Code:
\`\`\`${lang}
${code}
\`\`\``
},
error: {
title: '❌ Paste Your Error',
description: '🔧 Paste an error message and get a clear explanation of what went wrong.',
outputTitle: '🔧 Error Explained',
prompt: (code, lang) => `You are a helpful debugging assistant. A beginner programmer got this error and doesn't understand it.
Explain this error in a very beginner-friendly way:
1. **🔍 What the error means** — translate the technical message into simple English
2. **❓ Why it happened** — common causes for this type of error
3. **✅ How to fix it** — step-by-step solutions with code examples
4. **💡 Pro tip** — how to avoid this error in the future
Use simple language, emojis for visual appeal, and markdown formatting.
If relevant code is included with the error, reference specific lines.
Error/Code:
\`\`\`
${code}
\`\`\``
}
};
// ============ EXAMPLE SNIPPETS ============
const examples = {
'python-loop': {
code: `# Calculate the sum of numbers from 1 to 10
total = 0
for i in range(1, 11):
total += i
print(f"Adding {i}, total is now {total}")
print(f"The final sum is: {total}")`,
lang: 'python'
},
'js-fetch': {
code: `// Fetch user data from an API
async function getUser(userId) {
try {
const response = await fetch(\`https://api.example.com/users/\${userId}\`);
if (!response.ok) {
throw new Error(\`HTTP error! status: \${response.status}\`);
}
const userData = await response.json();
console.log('User:', userData.name);
return userData;
} catch (error) {
console.error('Failed to fetch user:', error.message);
}
}
getUser(42);`,
lang: 'javascript'
},
'java-class': {
code: `public class Student {
private String name;
private int age;
private double gpa;
public Student(String name, int age, double gpa) {
this.name = name;
this.age = age;
this.gpa = gpa;
}
public boolean isHonorRoll() {
return this.gpa >= 3.5;
}
@Override
public String toString() {
return name + " (Age: " + age + ", GPA: " + gpa + ")";
}
}`,
lang: 'java'
},
'rust-enum': {
code: `// Define a Rust enum with associative data
enum WebEvent {
PageLoad,
KeyPress(char),
Click { x: i64, y: i64 },
}
fn inspect_event(event: WebEvent) {
match event {
WebEvent::PageLoad => println!("page loaded"),
WebEvent::KeyPress(c) => println!("pressed key: {}", c),
WebEvent::Click { x, y } => {
println!("clicked at x={}, y={}", x, y);
}
}
}`,
lang: 'rust'
},
'go-routine': {
code: `package main
import (
"fmt"
"time"
)
func worker(id int) {
fmt.Printf("Worker %d starting\\n", id)
time.Sleep(time.Second)
fmt.Printf("Worker %d done\\n", id)
}
func main() {
go worker(1)
go worker(2)
// Wait for goroutines to finish
time.Sleep(2 * time.Second)
}`,
lang: 'go'
},
'error-msg': {
code: `Traceback (most recent call last):
File "app.py", line 15, in <module>
result = calculate_average(numbers)
File "app.py", line 8, in calculate_average
return sum(numbers) / len(numbers)
ZeroDivisionError: division by zero`,
lang: 'auto'
},
'cpp-template': {
code: `// A simple C++ template function
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}`,
lang: 'cpp'
},
'bash-script': {
code: `#!/bin/bash
# Check if directory exists
DIR="/var/log"
if [ -d "$DIR" ]; then
echo "Directory $DIR exists."
ls -la "$DIR" | head -n 5
else
echo "Directory $DIR does not exist."
fi`,
lang: 'bash'
}
};
// ============ INITIALIZATION ============
/**
* Initializes the application.
* Checks for a saved Groq API key in localStorage.
* Sets up all necessary DOM event listeners.
* Performs the initial character count for the code input.
*/
function init() {
// Entry point of the application.
// Check for API key on startup. If not found, prompt the user.
if (!apiKey) {
showApiKeyModal();
}
// Bind all UI events to their listeners.
setupEventListeners();
// Initialize the character count display.
updateCharCount();
// Set the current year in the footer.
const yearEl = document.getElementById('current-year');
if (yearEl) {
yearEl.textContent = new Date().getFullYear();
}
}
/**
* Attaches event listeners to all interactive DOM elements.
* Handles mode switching, API calls, clearing input, copying results,
* character counting, example loading, and keyboard shortcuts.
*/
function setupEventListeners() {
setupModeListeners();
setupActionListeners();
setupInputListeners();
setupModalListeners();
}
function setupModeListeners() {
elements.modeTabs.forEach(tab => {
tab.addEventListener('click', () => switchMode(tab.dataset.mode));
});
elements.exampleChips.forEach(chip => {
chip.addEventListener('click', () => loadExample(chip.dataset.example));
});
}
function setupActionListeners() {
elements.btnExplain.addEventListener('click', handleExplain);
elements.btnClear.addEventListener('click', () => {
if (elements.codeInput.value.trim() !== '') {
if (confirm('Are you sure you want to clear the code input?')) {
elements.codeInput.value = '';
updateCharCount();
elements.codeInput.focus();
showToast('🗑️ Input cleared');
}
} else {
elements.codeInput.focus();
}
});
elements.btnCopy.addEventListener('click', copyExplanation);
if (elements.btnDownload) {
elements.btnDownload.addEventListener('click', downloadExplanation);
}
if (elements.btnResetApi) {
elements.btnResetApi.addEventListener('click', () => {
if (confirm('Are you sure you want to reset and delete your stored API key?')) {
localStorage.removeItem('groq_api_key');
apiKey = '';
showApiKeyModal();
showToast('🔑 API key reset');
}
});
}
}
function setupInputListeners() {
elements.codeInput.addEventListener('input', updateCharCount);
elements.codeInput.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
handleExplain();
}
// Alt + C keyboard shortcut to clear the code input
if (e.altKey && e.key.toLowerCase() === 'c') {
e.preventDefault();
elements.btnClear.click();
}
});
}
function setupModalListeners() {
elements.btnSaveKey.addEventListener('click', saveApiKey);
elements.apiKeyInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') saveApiKey();
});
}
// ============ MODE SWITCHING ============
/**
* Switches the active explanation mode.
* Updates the UI tabs, title, description, and placeholder text
* based on the selected mode (e.g., 'explain', 'eli5', 'error').
*
* @param {string} mode - The mode identifier to switch to.
*/
function switchMode(mode) {
currentMode = mode;
// Update active tab
elements.modeTabs.forEach(tab => {
const isActive = tab.dataset.mode === mode;
tab.classList.toggle('active', isActive);
tab.setAttribute('aria-selected', isActive ? 'true' : 'false');
});
// Update UI text
const config = modeConfigs[mode];
elements.inputTitle.textContent = config.title;
elements.modeDescText.textContent = config.description;
// If switching to error mode, update placeholder
if (mode === 'error') {
elements.codeInput.placeholder = '// Paste your error message here...\n// You can also include the code that caused the error\n\nTraceback (most recent call last):\n File "app.py", line 5\n print("Hello")\nSyntaxError: unexpected EOF';
} else {
elements.codeInput.placeholder = '// Paste your code here...\n// Supports Python, JavaScript, Java, C++, and more!\n\nfunction greet(name) {\n return \'Hello, \' + name + \'!\';\n}';
}
}
// ============ EXAMPLE LOADING ============
/**
* Loads a predefined code example into the input area.
* Automatically switches the mode if an error example is selected.
*
* @param {string} exampleKey - The key identifying the example to load.
*/
function loadExample(exampleKey) {
const example = examples[exampleKey];
if (!example) return;
// Switch to error mode if loading error example
if (exampleKey === 'error-msg') {
switchMode('error');
} else if (currentMode === 'error') {
switchMode('explain');
}
elements.codeInput.value = example.code;
// Set language
if (example.lang !== 'auto') {
elements.languageSelect.value = example.lang;
} else {
elements.languageSelect.value = 'auto';
}
updateCharCount();
// Visual feedback
elements.codeInput.focus();
showToast('✨ Example loaded! Click Explain to see the magic');
}
// ============ MAIN EXPLAIN HANDLER ============
/**
* Main handler for the "Explain" button click.
* Validates the input and API key, determines the selected programming language,
* constructs the appropriate prompt based on the current mode, and
* makes an asynchronous call to the Groq API to retrieve the explanation.
* It also handles UI loading states and errors.
*/
function getCacheKey(code, mode, lang) {
const str = `${mode}_${lang}_${code}`;
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = (hash << 5) - hash + str.charCodeAt(i);
hash |= 0;
}
return 'cache_' + hash;
}
async function handleExplain() {
const code = elements.codeInput.value.trim();
if (!code) {
showToast('⚠️ Please paste some code first!');
elements.codeInput.focus();
return;
}
if (!apiKey) {
showApiKeyModal();
return;
}
// Get language
let lang = elements.languageSelect.value;
if (lang === 'auto') lang = 'the detected programming language';
// Check cache
const cacheKey = getCacheKey(code, currentMode, lang);
let cache = {};
try {
cache = JSON.parse(localStorage.getItem('explain_my_code_cache') || '{}');
} catch (e) {
console.error('Failed to parse cache:', e);
}
const config = modeConfigs[currentMode];
elements.outputTitle.textContent = config.outputTitle;
if (cache[cacheKey]) {
showToast('⚡ Loaded from cache!');
renderOutput(cache[cacheKey]);
return;
}
// Build prompt
const prompt = config.prompt(code, lang);
// UI loading state
setLoading(true);
showOutput('');
try {
const response = await callGroqAPI(prompt);
const explanation = response;
// Save to cache
try {
cache[cacheKey] = explanation;
const keys = Object.keys(cache);
if (keys.length > 25) {
delete cache[keys[0]];
}
localStorage.setItem('explain_my_code_cache', JSON.stringify(cache));
} catch (e) {
console.error('Failed to save to cache:', e);
}
// Render the output with markdown
renderOutput(explanation);
showToast('✅ Explanation ready!');
} catch (error) {
console.error('API Error:', error);
let errorMsg = '## ❌ Oops! Something went wrong\n\n';
if (error.message.includes('Invalid API') || error.message.includes('invalid_api_key') || error.message.includes('401')) {
errorMsg += 'Your API key seems invalid. Please check it and try again.\n\n';
errorMsg += '**Get a free key from:** [console.groq.com/keys](https://console.groq.com/keys)';
// Reset key
localStorage.removeItem('groq_api_key');
apiKey = '';
} else if (error.message.includes('rate') || error.message.includes('429')) {
errorMsg += '⏳ You\'ve hit the API rate limit. Please wait 30-60 seconds and try again.\n\n';
errorMsg += 'Groq free tier allows ~30 requests per minute.';
} else {
errorMsg += `**Error:** ${error.message}\n\n`;
errorMsg += 'Please check your internet connection and try again.';
}
renderOutput(errorMsg);
showToast('❌ Failed to get explanation');
} finally {
setLoading(false);
}
}
// ============ GROQ API CALL ============
/**
* Makes an asynchronous POST request to the Groq API.
* Uses the Llama 3.3 model to generate code explanations.
*
* @param {string} prompt - The formatted prompt string to send to the AI model.
* @returns {Promise<string>} A promise that resolves to the generated explanation text.
* @throws {Error} Throws an error if the API request fails (e.g., invalid key, rate limit).
*/
async function callGroqAPI(prompt) {
const response = await fetch(GROQ_API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: GROQ_MODEL,
messages: [
{
// System message sets the behavior and persona of the AI.
role: 'system',
content: 'You are a helpful coding teacher who explains code in a clear, beginner-friendly way. Always use markdown formatting in your responses.'
},
{
// User message contains the actual prompt constructed based on the mode.
role: 'user',
content: prompt
}
],
temperature: 0.7,
max_tokens: 4096,
})
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
const errorMessage = errorData?.error?.message || `HTTP ${response.status}`;
if (response.status === 401) {
throw new Error('Invalid API key (401)');
}
if (response.status === 429) {
throw new Error('Rate limit exceeded (429)');
}
throw new Error(errorMessage);
}
const data = await response.json();
// Extract text from Groq response (OpenAI-compatible format)
const text = data?.choices?.[0]?.message?.content;
if (!text) {
throw new Error('No response generated. Please try again.');
}
return text;
}
// ============ RENDERING ============
/**
* Parses and renders Markdown text into HTML.
* Uses Marked.js for markdown parsing and highlight.js for syntax highlighting
* within code blocks. Safely injects the parsed HTML into the output section.
*
* @param {string} markdownText - The raw markdown text from the AI response.
*/
function renderOutput(markdownText) {
elements.outputSection.style.display = 'block';
// Configure marked for safe rendering and syntax highlighting.
marked.setOptions({
highlight: function(code, lang) {
// If the language is detected and supported by highlight.js, use it.
if (lang && hljs.getLanguage(lang)) {
return hljs.highlight(code, { language: lang }).value;
}
// Otherwise, auto-detect the language.
return hljs.highlightAuto(code).value;
},
breaks: true, // Convert \n to <br>
gfm: true, // Enable GitHub Flavored Markdown
});
// Render markdown to HTML
const html = marked.parse(markdownText);
elements.outputContent.innerHTML = html;
// Highlight any code blocks
elements.outputContent.querySelectorAll('pre code').forEach((block) => {
hljs.highlightElement(block);
});
// Smooth scroll to output
elements.outputSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
/**
* Displays the output section with the provided content.
* Used primarily to show loading states or fallback messages before the
* markdown is fully rendered.
*
* @param {string} [content] - Optional HTML content to display.
*/
function showOutput(content) {
elements.outputSection.style.display = 'block';
elements.outputContent.innerHTML = content || '<p style="color: var(--text-muted); text-align: center;"><span class="spinner"></span> Thinking... this may take a few seconds</p>';
}
// ============ UI HELPERS ============
/**
* Toggles the UI loading state.
* Disables the explain button and shows a loading spinner during API calls.
*
* @param {boolean} loading - True to show loading state, false to hide it.
*/
function setLoading(loading) {
isLoading = loading;
const btnText = elements.btnExplain.querySelector('.btn-text');
const btnLoading = elements.btnExplain.querySelector('.btn-loading');
elements.btnExplain.disabled = loading;
btnText.style.display = loading ? 'none' : 'inline';
btnLoading.style.display = loading ? 'inline-flex' : 'none';
}
/**
* Updates the character and word count display based on the current code input.
* Triggered on every input event in the code textarea.
*/
function updateCharCount() {
const text = elements.codeInput.value.trim();
const length = elements.codeInput.value.length;
elements.charCount.textContent = length;
// Add character limit warning
if (length > 5000) {
elements.charCount.classList.add('exceeded');
elements.charCount.textContent = length + ' (Exceeds recommended limit!)';
} else {
elements.charCount.classList.remove('exceeded');
}
// Count words: split by whitespace and filter out empty strings
const words = text ? text.split(/\s+/).length : 0;
if (elements.wordCount) {
elements.wordCount.textContent = words;
}
}
/**
* Displays a temporary toast notification message on the screen.
* The toast automatically disappears after 3 seconds.
*
* @param {string} message - The text message to display in the toast.
*/
function showToast(message) {
// Remove existing toast
const existingToast = document.querySelector('.toast');
if (existingToast) existingToast.remove();
const toast = document.createElement('div');
toast.className = 'toast';
toast.textContent = message;
document.body.appendChild(toast);
// Trigger animation
requestAnimationFrame(() => {
toast.classList.add('show');
});
// Remove after 3s
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 300);
}, 3000);
}
// ============ API KEY MANAGEMENT ============
/**
* Displays the modal dialogue prompting the user to enter their Groq API key.
* Automatically focuses the input field for convenience.
*/
function showApiKeyModal() {
elements.apiKeyModal.style.display = 'flex';
setTimeout(() => elements.apiKeyInput.focus(), 100);
}
/**
* Validates and saves the entered Groq API key to localStorage.
* Dismisses the modal and shows a success toast upon successful save.
*/
function saveApiKey() {
const key = elements.apiKeyInput.value.trim();
if (!key) {
showToast('⚠️ Please enter your API key');
return;
}
apiKey = key;
localStorage.setItem('groq_api_key', key);
elements.apiKeyModal.style.display = 'none';
showToast('🔑 API key saved! You\'re ready to go');
}
// ============ COPY FUNCTIONALITY ============
/**
* Copies the current explanation content to the user's clipboard.
* Uses the modern navigator.clipboard API with a fallback mechanism
* using document.execCommand('copy') for older browsers.
*/
function copyExplanation() {
const text = elements.outputContent.innerText;
const setCopySuccess = () => {
showToast('📋 Explanation copied!');
const originalContent = elements.btnCopy.textContent;
elements.btnCopy.textContent = '✅';
setTimeout(() => {
elements.btnCopy.textContent = originalContent;
}, 2000);
};
navigator.clipboard.writeText(text).then(setCopySuccess).catch(() => {
// Fallback
const textarea = document.createElement('textarea');
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
textarea.remove();
setCopySuccess();
});
}
// ============ DOWNLOAD FUNCTIONALITY ============
/**
* Downloads the current explanation content as a Markdown (.md) file.
*/
function downloadExplanation() {
const text = elements.outputContent.innerText;
if (!text) {
showToast('⚠️ Nothing to download!');
return;
}
const blob = new Blob([text], { type: 'text/markdown;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
// Generate filename based on current mode and date
const dateStr = new Date().toISOString().slice(0, 10);
link.href = url;
link.setAttribute('download', `explanation-${currentMode}-${dateStr}.md`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
showToast('📥 Download started!');
}
// ============ START APP ============
init();