-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsidepanel.js
More file actions
575 lines (498 loc) · 20.5 KB
/
sidepanel.js
File metadata and controls
575 lines (498 loc) · 20.5 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
// DSA Hints Coach - Main Application
// This file contains the main functionality for the DSA Hints Coach extension
class DSACoach {
constructor() {
this.config = new Config();
this.apiService = null;
this.currentHints = [];
this.isLoading = false;
this.init();
}
async init() {
this.setupEventListeners();
await this.config.init();
this.apiService = new ApiService(this.config);
await this.loadHistory();
this.setupMessageListener();
// Check if API key is needed
if (!this.config.hasValidApiKey()) {
this.showApiKeyPrompt();
}
}
setupEventListeners() {
const getHintBtn = document.getElementById('get-hint-btn');
const clearBtn = document.getElementById('clear-btn');
const problemTextarea = document.getElementById('problem-statement');
if (getHintBtn) {
getHintBtn.addEventListener('click', () => this.handleGetHint());
}
if (clearBtn) {
clearBtn.addEventListener('click', () => this.handleClear());
}
if (problemTextarea) {
problemTextarea.addEventListener('input', () => this.handleTextareaInput());
}
}
setupMessageListener() {
// Listen for messages from content script
if (chrome.runtime && chrome.runtime.onMessage) {
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'PROBLEM_DETECTED') {
this.handleProblemDetected(message.problem);
sendResponse({ success: true });
}
});
}
}
showApiKeyPrompt() {
// Remove existing API key section if present
const existingSection = document.querySelector('.api-key-section');
if (existingSection) {
existingSection.remove();
}
const container = document.querySelector('.container');
if (!container) return;
const apiKeySection = document.createElement('div');
apiKeySection.className = 'api-key-section';
apiKeySection.innerHTML = `
<div class="api-key-prompt">
<h3>🔑 API Key Required</h3>
<p>Please enter your Gemini API key to use this extension:</p>
<input type="password" id="api-key-input" placeholder="Enter Gemini API Key" />
<button id="save-api-key-btn" class="btn btn-primary">Save & Test API Key</button>
<div id="api-key-status" class="api-key-status"></div>
<p class="api-key-help">
<a href="https://makersuite.google.com/app/apikey" target="_blank">
Get your API key from Google AI Studio
</a>
</p>
</div>
`;
container.insertBefore(apiKeySection, container.firstChild);
const saveBtn = document.getElementById('save-api-key-btn');
if (saveBtn) {
saveBtn.addEventListener('click', () => this.saveApiKey());
}
// Add enter key support
const apiKeyInput = document.getElementById('api-key-input');
if (apiKeyInput) {
apiKeyInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.saveApiKey();
}
});
}
}
async saveApiKey() {
const apiKeyInput = document.getElementById('api-key-input');
const saveBtn = document.getElementById('save-api-key-btn');
const apiKey = apiKeyInput ? apiKeyInput.value.trim() : '';
if (!apiKey) {
this.showApiKeyStatus('Please enter a valid API key', 'error');
return;
}
// Show loading state
if (saveBtn) {
saveBtn.disabled = true;
saveBtn.textContent = 'Testing...';
}
this.showApiKeyStatus('Testing API key...', 'info');
try {
// Test the API key first
const testResult = await this.apiService.testApiKey(apiKey);
if (!testResult.valid) {
this.showApiKeyStatus(`Invalid API key: ${testResult.error}`, 'error');
if (saveBtn) {
saveBtn.disabled = false;
saveBtn.textContent = 'Save & Test API Key';
}
return;
}
// Save the API key
const saved = await this.config.saveApiKey(apiKey);
if (saved) {
this.showApiKeyStatus('API key saved and tested successfully!', 'success');
setTimeout(() => {
const section = document.querySelector('.api-key-section');
if (section) {
section.remove();
}
this.showNotification('API key configured successfully!', 'success');
}, 1500);
} else {
this.showApiKeyStatus('Failed to save API key', 'error');
}
} catch (error) {
console.error('Error saving API key:', error);
this.showApiKeyStatus(`Error: ${error.message}`, 'error');
} finally {
if (saveBtn) {
saveBtn.disabled = false;
saveBtn.textContent = 'Save & Test API Key';
}
}
}
showApiKeyStatus(message, type) {
const statusDiv = document.getElementById('api-key-status');
if (statusDiv) {
statusDiv.textContent = message;
statusDiv.className = `api-key-status api-key-status-${type}`;
}
}
async handleGetHint() {
if (!this.config.hasValidApiKey()) {
this.showNotification('Please set your API key first', 'error');
this.showApiKeyPrompt();
return;
}
const problemStatementElement = document.getElementById('problem-statement');
const problemStatement = problemStatementElement ? problemStatementElement.value.trim() : '';
if (!problemStatement) {
this.showNotification('Please enter a problem statement', 'error');
return;
}
if (this.isLoading) return;
this.setLoadingState(true);
try {
const hints = await this.apiService.generateHints(problemStatement);
this.displayHints(hints);
await this.saveToHistory(problemStatement, hints);
} catch (error) {
console.error('Error generating hints:', error);
// Handle specific error types
if (error.message.includes('Invalid API key')) {
this.showNotification('Invalid API key. Please check your settings.', 'error');
this.showApiKeyPrompt();
} else if (error.message.includes('Rate limit')) {
this.showNotification('Rate limit exceeded. Please try again later.', 'error');
} else if (error.message.includes('Network error')) {
this.showNotification('Network error. Please check your internet connection.', 'error');
} else {
this.showNotification(`Failed to generate hints: ${error.message}`, 'error');
}
} finally {
this.setLoadingState(false);
}
}
displayHints(hints) {
const hintsContainer = document.getElementById('hints-container');
if (!hintsContainer) return;
if (!hints || hints.length === 0) {
hintsContainer.innerHTML = `
<div class="no-hints">
<p>Unable to generate hints. Please try again.</p>
</div>
`;
return;
}
const hintsHTML = hints.map(hint => `
<div class="hint-item">
<div class="hint-header">
<div class="hint-number hint-${hint.number}">${hint.number}</div>
<div class="hint-title">
${this.getHintTitle(hint.number)}
</div>
</div>
<div class="hint-content">${hint.content}</div>
</div>
`).join('');
hintsContainer.innerHTML = hintsHTML;
this.currentHints = hints;
}
getHintTitle(hintNumber) {
const titles = {
1: 'General Direction',
2: 'Data Structure/Algorithm',
3: 'Optimization/Edge Cases'
};
return titles[hintNumber] || `Hint ${hintNumber}`;
}
async saveToHistory(problemStatement, hints) {
try {
const historyItem = {
id: Date.now(),
problem: problemStatement.substring(0, 100) + (problemStatement.length > 100 ? '...' : ''),
hints: hints,
timestamp: new Date().toISOString()
};
if (chrome.storage && chrome.storage.local) {
const result = await chrome.storage.local.get(['queryHistory']);
const history = result.queryHistory || [];
// Add new item at the beginning
history.unshift(historyItem);
// Keep only last 10 items
if (history.length > 10) {
history.splice(10);
}
await chrome.storage.local.set({ queryHistory: history });
this.displayHistory(history);
} else {
// Fallback: store in memory
if (!this.memoryHistory) this.memoryHistory = [];
this.memoryHistory.unshift(historyItem);
if (this.memoryHistory.length > 10) {
this.memoryHistory.splice(10);
}
this.displayHistory(this.memoryHistory);
}
} catch (error) {
console.error('Error saving to history:', error);
}
}
async loadHistory() {
try {
if (chrome.storage && chrome.storage.local) {
const result = await chrome.storage.local.get(['queryHistory']);
const history = result.queryHistory || [];
this.displayHistory(history);
} else if (this.memoryHistory) {
this.displayHistory(this.memoryHistory);
}
} catch (error) {
console.error('Error loading history:', error);
}
}
displayHistory(history) {
const historyContainer = document.getElementById('history-container');
if (!historyContainer) return;
if (history.length === 0) {
historyContainer.innerHTML = '<p class="no-history">No queries yet</p>';
return;
}
const historyHTML = history.map(item => `
<div class="history-item" data-id="${item.id}">
<div class="history-text">${item.problem}</div>
<div class="history-timestamp">${this.formatTimestamp(item.timestamp)}</div>
</div>
`).join('');
historyContainer.innerHTML = historyHTML;
// Add click listeners to history items
historyContainer.querySelectorAll('.history-item').forEach(item => {
item.addEventListener('click', () => {
this.loadHistoryItem(item.dataset.id);
});
});
}
async loadHistoryItem(id) {
try {
let history = [];
if (chrome.storage && chrome.storage.local) {
const result = await chrome.storage.local.get(['queryHistory']);
history = result.queryHistory || [];
} else if (this.memoryHistory) {
history = this.memoryHistory;
}
const item = history.find(h => h.id === parseInt(id));
if (item) {
const problemElement = document.getElementById('problem-statement');
if (problemElement) {
problemElement.value = item.problem;
}
this.displayHints(item.hints);
}
} catch (error) {
console.error('Error loading history item:', error);
}
}
formatTimestamp(timestamp) {
const date = new Date(timestamp);
const now = new Date();
const diffMs = now - date;
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 1) return 'Just now';
if (diffMins < 60) return `${diffMins}m ago`;
if (diffHours < 24) return `${diffHours}h ago`;
if (diffDays < 7) return `${diffDays}d ago`;
return date.toLocaleDateString();
}
handleClear() {
const problemElement = document.getElementById('problem-statement');
const hintsContainer = document.getElementById('hints-container');
if (problemElement) {
problemElement.value = '';
}
if (hintsContainer) {
hintsContainer.innerHTML = `
<div class="no-hints">
<p>Click "Get Hint" to receive progressive guidance</p>
</div>
`;
}
this.currentHints = [];
}
handleTextareaInput() {
const textarea = document.getElementById('problem-statement');
const getHintBtn = document.getElementById('get-hint-btn');
if (textarea && getHintBtn) {
// Enable/disable button based on content
getHintBtn.disabled = !textarea.value.trim();
}
}
handleProblemDetected(problem) {
// Store the detected problem but don't auto-fill
this.detectedProblem = problem;
// Show notification with option to load
this.showProblemDetectedNotification(problem);
}
showProblemDetectedNotification(problem) {
// Create a notification with load button
const notification = document.createElement('div');
notification.className = 'notification notification-info';
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
padding: 16px 24px;
border-radius: 12px;
color: var(--text-primary);
font-weight: 600;
z-index: 1000;
animation: slideInRight 0.3s ease;
max-width: 350px;
background: rgba(59, 130, 246, 0.9);
border: 1px solid #3b82f6;
backdrop-filter: blur(20px);
`;
const problemPreview = problem.substring(0, 100) + (problem.length > 100 ? '...' : '');
notification.innerHTML = `
<div style="margin-bottom: 12px;">
<strong>🧠 Problem Detected!</strong>
</div>
<div style="font-size: 14px; margin-bottom: 12px; opacity: 0.9;">
${problemPreview}
</div>
<div style="display: flex; gap: 8px;">
<button id="load-problem-btn" style="
background: rgba(255, 255, 255, 0.2);
border: 1px solid rgba(255, 255, 255, 0.3);
color: white;
padding: 6px 12px;
border-radius: 6px;
cursor: pointer;
font-size: 12px;
font-weight: 500;
">Load Problem</button>
<button id="dismiss-notification-btn" style="
background: transparent;
border: 1px solid rgba(255, 255, 255, 0.3);
color: white;
padding: 6px 12px;
border-radius: 6px;
cursor: pointer;
font-size: 12px;
font-weight: 500;
">Dismiss</button>
</div>
`;
document.body.appendChild(notification);
// Add event listeners
const loadBtn = notification.querySelector('#load-problem-btn');
const dismissBtn = notification.querySelector('#dismiss-notification-btn');
if (loadBtn) {
loadBtn.addEventListener('click', () => {
this.loadDetectedProblem();
this.removeNotification(notification);
});
}
if (dismissBtn) {
dismissBtn.addEventListener('click', () => {
this.removeNotification(notification);
});
}
// Auto-remove after 10 seconds
setTimeout(() => {
this.removeNotification(notification);
}, 10000);
}
loadDetectedProblem() {
if (this.detectedProblem) {
const problemElement = document.getElementById('problem-statement');
if (problemElement) {
problemElement.value = this.detectedProblem;
this.showNotification('Problem loaded successfully!', 'success');
}
}
}
removeNotification(notification) {
if (notification && notification.parentNode) {
notification.style.animation = 'slideOutRight 0.3s ease';
setTimeout(() => {
if (notification.parentNode) {
notification.parentNode.removeChild(notification);
}
}, 300);
}
}
setLoadingState(loading) {
this.isLoading = loading;
const getHintBtn = document.getElementById('get-hint-btn');
if (!getHintBtn) return;
const btnText = getHintBtn.querySelector('.btn-text');
const spinner = getHintBtn.querySelector('.loading-spinner');
if (loading) {
if (btnText) btnText.textContent = 'Generating...';
if (spinner) spinner.style.display = 'block';
getHintBtn.disabled = true;
} else {
if (btnText) btnText.textContent = 'Get Hint';
if (spinner) spinner.style.display = 'none';
getHintBtn.disabled = false;
}
}
showNotification(message, type = 'info') {
// Create notification element
const notification = document.createElement('div');
notification.className = `notification notification-${type}`;
notification.textContent = message;
// Add styles
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
padding: 12px 20px;
border-radius: 8px;
color: white;
font-weight: 500;
z-index: 1000;
animation: slideInRight 0.3s ease;
max-width: 300px;
`;
// Set background color based on type
const colors = {
success: '#10b981',
error: '#ef4444',
info: '#3b82f6'
};
notification.style.backgroundColor = colors[type] || colors.info;
document.body.appendChild(notification);
// Remove after 3 seconds
setTimeout(() => {
notification.style.animation = 'slideOutRight 0.3s ease';
setTimeout(() => {
if (notification.parentNode) {
notification.parentNode.removeChild(notification);
}
}, 300);
}, 3000);
}
}
// Add CSS animations for notifications
const style = document.createElement('style');
style.textContent = `
@keyframes slideInRight {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes slideOutRight {
from { transform: translateX(0); opacity: 1; }
to { transform: translateX(100%); opacity: 0; }
}
`;
document.head.appendChild(style);
// Initialize the app when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
console.log('Initializing DSA Hints Coach...');
new DSACoach();
});