-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathpopup.js
More file actions
336 lines (287 loc) · 10.3 KB
/
popup.js
File metadata and controls
336 lines (287 loc) · 10.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
let popupTimerInterval = null;
document.addEventListener('DOMContentLoaded', () => {
const apiKeyInput = document.getElementById('api-key');
const modelSelect = document.getElementById('model-select');
const customModelInput = document.getElementById("custom-model-input");
const ordinaryHintBtn = document.getElementById('ordinary-hint');
const advancedHintBtn = document.getElementById('advanced-hint');
const expertHintBtn = document.getElementById('expert-hint');
const hintContainer = document.getElementById('hint-container');
const hintText = document.getElementById('hint-text');
const errorContainer = document.getElementById('error-container');
const errorText = document.getElementById('error-text');
const settingsBtn = document.getElementById('settings-btn');
const closeSettingsBtn = document.getElementById('close-settings');
const mainView = document.getElementById('main-view');
const settingsView = document.getElementById('settings-view');
const aiTitle = document.getElementById('ai-title');
// Load saved settings (API key and model)
chrome.storage.local.get(['groq_api_key', 'selected_model'], (result) => {
if (result.groq_api_key) {
apiKeyInput.value = result.groq_api_key;
}
if (result.selected_model) {
const presets = ['llama3-8b-8192', 'gemma2-9b-it', 'deepseek-r1-distill-llama-70b'];
if (presets.includes(result.selected_model)) {
modelSelect.value = result.selected_model;
} else {
modelSelect.value = 'custom';
customModelInput.value = result.selected_model;
}
toggleCustomInput();
}
});
const resetPeriodInput = document.getElementById('reset-period');
chrome.storage.local.get(['resetPeriodDays'], (result) => {
if (result.resetPeriodDays) {
resetPeriodInput.value = result.resetPeriodDays;
}
});
// Save API key on change
apiKeyInput.addEventListener('change', () => {
chrome.storage.local.set({ 'groq_api_key': apiKeyInput.value });
});
modelSelect.addEventListener('change', toggleCustomInput);
toggleCustomInput(); // run once on startup
// Hint button clicks
ordinaryHintBtn.addEventListener('click', () => getHint('ordinary'));
advancedHintBtn.addEventListener('click', () => getHint('advanced'));
expertHintBtn.addEventListener('click', () => getHint('expert'));
function getHint(level) {
// Read the current allowed time first
chrome.storage.local.get(['timeAllowed'], function(result) {
const timeAllowed = result.timeAllowed || 0;
if (timeAllowed <= -5) {
showError('You have reached the hint limit! Solve a LeetCode problem to earn more time.');
return;
}
const apiKey = apiKeyInput.value;
const model = modelSelect.value === 'custom' ? customModelInput.value.trim() : modelSelect.value;
// Check if custom model field is empty
if (modelSelect.value === 'custom' && !model) {
showError('Please enter a custom model name.');
return;
}
if (!apiKey) {
showError('Please enter your Groq API key.');
return;
}
// Get the current leetcode problem
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript(
{
target: { tabId: tabs[0].id },
function: getProblemContext,
},
(results) => {
if (results && results[0] && results[0].result) {
const problemContext = results[0].result;
fetchHint(apiKey, model, level, problemContext);
} else {
showError('Could not get problem context from LeetCode page.');
}
}
);
});
});
}
async function fetchHint(apiKey, model, level, context) {
const cost = {
ordinary: 2,
advanced: 3,
expert: 5,
};
try {
const response = await fetch('https://api.groq.com/openai/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
body: JSON.stringify({
model,
messages: [
{
role: 'system',
content: `You are an AI assistant for LeetCode. Provide a ${level} hint for the following problem. Do not solve the entire problem. Just provide a hint.`,
},
{
role: 'user',
content: context,
},
],
}),
});
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}
const data = await response.json();
const hint = data.choices[0].message.content;
hintText.innerText = hint;
hintContainer.classList.remove('hidden');
errorContainer.classList.add('hidden');
// Deduct time
chrome.runtime.sendMessage({ type: 'deductTime', cost: cost[level] });
loadTimerFromStorage();
} catch (error) {
showError(error.message);
}
}
function showError(message) {
errorText.innerText = message;
errorContainer.classList.remove('hidden');
hintContainer.classList.add('hidden');
}
function toggleCustomInput() {
if (modelSelect.value === 'custom') {
customModelInput.style.display = 'block';
customModelInput.focus();
} else {
customModelInput.style.display = 'none';
customModelInput.value = '';
}
}
// Settings page navigation
settingsBtn.addEventListener('click', () => {
document.querySelector('.container').style.display = 'none';
settingsView.style.display = 'block';
});
closeSettingsBtn.addEventListener('click', () => {
settingsView.style.display = 'none';
document.querySelector('.container').style.display = 'flex';
// Make sure container keeps its layout
const container = document.querySelector('.container');
if (container) {
container.style.flexDirection = 'column';
container.style.gap = '15px';
}
// Check if we're on leetcode again
setTimeout(() => {
checkIfLeetCode();
}, 50);
});
// Save settings button
const saveSettingsBtn = document.getElementById('save-settings');
saveSettingsBtn.addEventListener('click', () => {
const apiKey = apiKeyInput.value.trim();
const selectedModel = modelSelect.value === 'custom' ? customModelInput.value.trim() : modelSelect.value;
if (!apiKey) {
alert('Please enter your Groq API key before saving.');
return;
}
if (modelSelect.value === 'custom' && !selectedModel) {
alert('Please enter a custom model name before saving.');
return;
}
const resetPeriod = Math.max(1, parseInt(resetPeriodInput.value, 10) || 7);
chrome.storage.local.set({
groq_api_key: apiKey,
selected_model: selectedModel,
resetPeriodDays: resetPeriod
}, () => {
alert('Settings saved successfully!');
chrome.runtime.sendMessage({ type: 'updateResetPeriod', period: resetPeriod });
});
});
function startRealtimeTimer() {
if (popupTimerInterval) {
clearInterval(popupTimerInterval);
}
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
const currentUrl = tabs[0].url;
if (isSocialMediaSite(currentUrl)) {
loadTimerFromStorage();
// Update timer every second
popupTimerInterval = setInterval(function () {
loadTimerFromStorage();
}, 1000);
} else {
// Just load once for non-social media sites
loadTimerFromStorage();
}
});
}
function isSocialMediaSite(url) {
if (!url) return false;
try {
const urlObj = new URL(url);
return (
urlObj.hostname.includes('youtube.com') ||
urlObj.hostname.includes('instagram.com') ||
urlObj.hostname.includes('twitter.com') ||
urlObj.hostname.includes('x.com') ||
urlObj.hostname.includes('facebook.com') ||
urlObj.hostname.includes('webnovel.com') ||
urlObj.hostname.includes('novelbin.com')
);
} catch (e) {
return false;
}
}
// Listen for tab changes
chrome.tabs.onActivated.addListener(function (activeInfo) {
setTimeout(() => {
startRealtimeTimer();
}, 100);
});
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status === 'complete') {
setTimeout(() => {
startRealtimeTimer();
}, 100);
}
});
// Startup
checkIfLeetCode();
startRealtimeTimer();
chrome.storage.onChanged.addListener(function (changes, areaName) {
if (areaName === 'local' && changes.timeAllowed) {
updateTimerDisplay(changes.timeAllowed.newValue || 0);
}
});
});
const hintsSection = document.querySelector('.hints');
const aiTitle = document.getElementById('ai-title');
function checkIfLeetCode() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (!tabs || !tabs[0] || !tabs[0].url) {
return;
}
const url = tabs[0].url;
const isLeet = url.indexOf('leetcode.com/problems/') !== -1;
const aiBox = document.querySelector('.ai-box');
if (isLeet) {
if (aiBox && aiBox.style.display === 'none') {
aiBox.style.display = 'block';
}
} else {
if (aiBox && aiBox.style.display !== 'none') {
aiBox.style.display = 'none';
}
}
});
}
// Problem details from leetcode page
function getProblemContext() {
const titleElement = Array.from(document.querySelectorAll('a')).find(a => a.href.includes('/problems/'));
const questionTitle = titleElement ? titleElement.innerText : 'Title not found';
const questionContent = document.querySelector('[data-track-load="description_content"]').innerText;
return `Title: ${questionTitle}\n\n${questionContent}`;
}
// Timer
function updateTimerDisplay(timeInSeconds) {
timeInSeconds = Math.max(0, timeInSeconds);
const timerElement = document.getElementById('timer');
if (timerElement) {
const minutes = Math.floor(timeInSeconds / 60);
const seconds = timeInSeconds % 60;
const formattedTime = minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0');
timerElement.textContent = formattedTime;
}
}
function loadTimerFromStorage() {
chrome.storage.local.get(['timeAllowed'], function (result) {
const timeAllowed = result.timeAllowed || 0;
updateTimerDisplay(timeAllowed);
});
}