-
Notifications
You must be signed in to change notification settings - Fork 138
Expand file tree
/
Copy pathbackground.js
More file actions
675 lines (616 loc) · 23.9 KB
/
Copy pathbackground.js
File metadata and controls
675 lines (616 loc) · 23.9 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
// Handle context menu for highlighted text translation
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "translateToHinglish",
title: "Translate to Hinglish",
contexts: ["selection"],
});
chrome.contextMenus.create({
id: "explainInHinglish",
title: "Explain in Hinglish",
contexts: ["selection"],
});
});
// Handle messages from content script and popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "translateText") {
translateText(request.text)
.then(sendResponse)
.catch((error) => {
console.error("Translation error:", error);
sendResponse("Translation error: " + error.message);
});
return true; // Required for async sendResponse
}
if (request.action === "explainText") {
explainText(request.text)
.then(sendResponse)
.catch((error) => {
console.error("Explanation error:", error);
sendResponse("Explanation error: " + error.message);
});
return true; // Required for async sendResponse
}
});
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.menuItemId === "translateToHinglish" && info.selectionText) {
try {
// Show loading popup with progress bar
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: showLoadingPopup,
args: [],
});
// Simulate progress updates
let progress = 0;
const progressInterval = setInterval(() => {
progress = Math.min(progress + 10, 90); // Cap at 90% until API response
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: updateProgress,
args: [progress],
});
}, 200);
const translatedText = await translateText(info.selectionText);
// Clear progress interval and set to 100%
clearInterval(progressInterval);
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: updateProgress,
args: [100],
});
// Remove loading popup and show translation
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: showTranslationPopup,
args: [info.selectionText, translatedText],
});
} catch (error) {
console.error("Context menu translation error:", error);
// Show error in popup
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: showErrorPopup,
args: [error.message],
});
}
} else if (info.menuItemId === "explainInHinglish" && info.selectionText) {
try {
// Show loading popup with progress bar
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: showLoadingPopup,
args: [],
});
// Simulate progress updates
let progress = 0;
const progressInterval = setInterval(() => {
progress = Math.min(progress + 10, 90);
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: updateProgress,
args: [progress],
});
}, 200);
const explanation = await explainText(info.selectionText);
// Clear progress interval and set to 100%
clearInterval(progressInterval);
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: updateProgress,
args: [100],
});
// Remove loading popup and show explanation
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: showExplanationPopup,
args: [info.selectionText, explanation],
});
} catch (error) {
console.error("Context menu explanation error:", error);
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: showErrorPopup,
args: [error.message],
});
}
}
});
// Function to get translation prompt based on style and level
function getTranslationPrompt(style, level) {
const prompts = {
hinglish: {
balanced:
"You are a translator that converts English text to Hinglish (Hindi written in English letters). Keep the meaning exactly the same but make it sound natural in Hinglish. Use a balanced mix of Hindi and English words. Only respond with the translated text, no explanations.",
moreHindi:
"You are a translator that converts English text to Hinglish (Hindi written in English letters). Keep the meaning exactly the same but make it sound natural in Hinglish. Use more Hindi words than English. Only respond with the translated text, no explanations.",
moreEnglish:
"You are a translator that converts English text to Hinglish (Hindi written in English letters). Keep the meaning exactly the same but make it sound natural in Hinglish. Use more English words than Hindi. Only respond with the translated text, no explanations.",
},
hindi: {
balanced:
"You are a translator that converts English text to Hindi (Devanagari script). Keep the meaning exactly the same but make it sound natural in Hindi. Use a balanced mix of formal and colloquial Hindi. Only respond with the translated text, no explanations.",
moreHindi:
"You are a translator that converts English text to Hindi (Devanagari script). Keep the meaning exactly the same but make it sound natural in Hindi. Use more formal Hindi words. Only respond with the translated text, no explanations.",
moreEnglish:
"You are a translator that converts English text to Hindi (Devanagari script). Keep the meaning exactly the same but make it sound natural in Hindi. Use more colloquial Hindi words. Only respond with the translated text, no explanations.",
},
roman: {
balanced:
"You are a translator that converts Hindi text to Romanized Hindi (Hindi written in English letters). Keep the meaning exactly the same but make it sound natural. Use a balanced mix of formal and colloquial words. Only respond with the translated text, no explanations.",
moreHindi:
"You are a translator that converts Hindi text to Romanized Hindi (Hindi written in English letters). Keep the meaning exactly the same but make it sound natural. Use more formal words. Only respond with the translated text, no explanations.",
moreEnglish:
"You are a translator that converts Hindi text to Romanized Hindi (Hindi written in English letters). Keep the meaning exactly the same but make it sound natural. Use more colloquial words. Only respond with the translated text, no explanations.",
},
formal: {
balanced:
"You are a translator that converts English text to formal Hinglish (Hindi written in English letters). Keep the meaning exactly the same but make it sound professional and formal. Use a balanced mix of Hindi and English words. Only respond with the translated text, no explanations.",
moreHindi:
"You are a translator that converts English text to formal Hinglish (Hindi written in English letters). Keep the meaning exactly the same but make it sound professional and formal. Use more Hindi words than English. Only respond with the translated text, no explanations.",
moreEnglish:
"You are a translator that converts English text to formal Hinglish (Hindi written in English letters). Keep the meaning exactly the same but make it sound professional and formal. Use more English words than Hindi. Only respond with the translated text, no explanations.",
},
casual: {
balanced:
"You are a translator that converts English text to casual Hinglish (Hindi written in English letters). Keep the meaning exactly the same but make it sound casual and conversational. Use a balanced mix of Hindi and English words. Only respond with the translated text, no explanations.",
moreHindi:
"You are a translator that converts English text to casual Hinglish (Hindi written in English letters). Keep the meaning exactly the same but make it sound casual and conversational. Use more Hindi words than English. Only respond with the translated text, no explanations.",
moreEnglish:
"You are a translator that converts English text to casual Hinglish (Hindi written in English letters). Keep the meaning exactly the same but make it sound casual and conversational. Use more English words than Hindi. Only respond with the translated text, no explanations.",
},
};
return prompts[style][level] || prompts.hinglish.balanced;
}
// Function to translate text using Groq API
async function translateText(text) {
const { groqApiKey, translationSettings } = await chrome.storage.local.get([
"groqApiKey",
"translationSettings",
]);
if (!groqApiKey) {
throw new Error("Please configure your API key first");
}
const style = translationSettings?.style || "hinglish";
const level = translationSettings?.level || "balanced";
const prompt = getTranslationPrompt(style, level);
try {
const response = await fetch(
"https://api.groq.com/openai/v1/chat/completions",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${groqApiKey}`,
},
body: JSON.stringify({
messages: [
{
role: "system",
content: prompt,
},
{
role: "user",
content: text,
},
],
model: "meta-llama/llama-4-scout-17b-16e-instruct",
temperature: 0.7,
max_tokens: 1000,
}),
}
);
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(
errorData.error?.message || `API error: ${response.status}`
);
}
const data = await response.json();
const translatedText = data.choices[0].message.content.trim();
if (!translatedText) {
throw new Error("Empty translation received");
}
return translatedText;
} catch (error) {
console.error("Translation error:", error);
throw error;
}
}
// Function to explain text using Groq API
async function explainText(text) {
const { groqApiKey, translationSettings } = await chrome.storage.local.get([
"groqApiKey",
"translationSettings",
]);
if (!groqApiKey) {
throw new Error("Please configure your API key first");
}
const style = translationSettings?.style || "hinglish";
const level = translationSettings?.level || "balanced";
const prompt = `You are an AI assistant that explains concepts in ${
style === "hindi" ? "Hindi" : "Hinglish"
}.
Provide a clear and detailed explanation of the given text.
Make it easy to understand and use ${
level === "moreHindi"
? "more Hindi words"
: level === "moreEnglish"
? "more English words"
: "a balanced mix of Hindi and English words"
}.
Format your response in a clear, structured way with bullet points or short paragraphs.
Only respond with the explanation, no additional text.`;
try {
const response = await fetch(
"https://api.groq.com/openai/v1/chat/completions",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${groqApiKey}`,
},
body: JSON.stringify({
messages: [
{
role: "system",
content: prompt,
},
{
role: "user",
content: text,
},
],
model: "meta-llama/llama-4-scout-17b-16e-instruct",
temperature: 0.7,
max_tokens: 1000,
}),
}
);
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(
errorData.error?.message || `API error: ${response.status}`
);
}
const data = await response.json();
const explanation = data.choices[0].message.content.trim();
if (!explanation) {
throw new Error("Empty explanation received");
}
return explanation;
} catch (error) {
console.error("Explanation error:", error);
throw error;
}
}
// Function to show loading popup
function showLoadingPopup() {
const popup = document.createElement("div");
popup.id = "translationLoadingPopup";
popup.style.position = "fixed";
popup.style.zIndex = "9999";
popup.style.borderRadius = "8px";
popup.style.padding = "20px";
popup.style.boxShadow = "0 4px 12px rgba(0,0,0,0.15)";
popup.style.maxWidth = "300px";
popup.style.fontFamily = "Arial, sans-serif";
popup.style.fontSize = "14px";
popup.style.top = "50%";
popup.style.left = "50%";
popup.style.transform = "translate(-50%, -50%)";
popup.style.textAlign = "center";
// Dark mode detection and styling
if (
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
) {
popup.style.backgroundColor = "#2d2d2d";
popup.style.color = "#ffffff";
popup.style.border = "1px solid #444";
} else {
popup.style.backgroundColor = "#ffffff";
popup.style.color = "#333333";
popup.style.border = "1px solid #ddd";
}
popup.innerHTML = `
<div style="margin-bottom: 15px; font-size: 15px;">Processing...</div>
<div id="progressBar" style="
background: rgba(0,0,0,0.1);
height: 8px;
border-radius: 4px;
overflow: hidden;
">
<div id="progressFill" style="
width: 0%;
height: 100%;
background: #1a73e8;
transition: width 0.3s ease-in-out;
"></div>
</div>
`;
document.body.appendChild(popup);
}
// Function to update progress bar
function updateProgress(progress) {
const progressFill = document.getElementById("progressFill");
if (progressFill) {
progressFill.style.width = `${progress}%`;
}
}
// Function to show translation popup
function showTranslationPopup(originalText, translatedText) {
// Remove loading popup if it exists
const loadingPopup = document.getElementById("translationLoadingPopup");
if (loadingPopup) {
document.body.removeChild(loadingPopup);
}
const popup = document.createElement("div");
popup.className = "hinglish-popup";
popup.style.position = "fixed";
popup.style.zIndex = "9999";
popup.style.borderRadius = "8px";
popup.style.padding = "20px";
popup.style.boxShadow = "0 4px 12px rgba(0,0,0,0.15)";
popup.style.maxWidth = "400px";
popup.style.fontFamily = "Arial, sans-serif";
popup.style.fontSize = "14px";
popup.style.top = "50%";
popup.style.left = "50%";
popup.style.transform = "translate(-50%, -50%)";
if (
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
) {
popup.style.backgroundColor = "#2d2d2d";
popup.style.color = "#ffffff";
popup.style.border = "1px solid #444";
popup.innerHTML = `
<div style="margin-bottom: 15px;">
<div style="font-weight: bold; margin-bottom: 8px; color: #aaa;">Original Text:</div>
<div style="background: #3a3a3a; padding: 12px; border-radius: 6px; margin-bottom: 15px; line-height: 1.5;">${originalText}</div>
<div style="font-weight: bold; margin-bottom: 8px; color: #aaa;">Translation:</div>
<div style="background: #1a3d6d; padding: 12px; border-radius: 6px; margin-bottom: 15px; line-height: 1.5;">${translatedText}</div>
</div>
<div style="text-align: right;">
<button id="closePopup" style="
cursor: pointer;
padding: 8px 16px;
background: #1a73e8;
color: white;
border: none;
border-radius: 4px;
font-size: 14px;
transition: background 0.2s;
">Close</button>
</div>
`;
} else {
popup.style.backgroundColor = "#ffffff";
popup.style.color = "#333333";
popup.style.border = "1px solid #ddd";
popup.innerHTML = `
<div style="margin-bottom: 15px;">
<div style="font-weight: bold; margin-bottom: 8px; color: #666;">Original Text:</div>
<div style="background: #f5f5f5; padding: 12px; border-radius: 6px; margin-bottom: 15px; line-height: 1.5;">${originalText}</div>
<div style="font-weight: bold; margin-bottom: 8px; color: #666;">Translation:</div>
<div style="background: #e8f0fe; padding: 12px; border-radius: 6px; margin-bottom: 15px; line-height: 1.5;">${translatedText}</div>
</div>
<div style="text-align: right;">
<button id="closePopup" style="
cursor: pointer;
padding: 8px 16px;
background: #1a73e8;
color: white;
border: none;
border-radius: 4px;
font-size: 14px;
transition: background 0.2s;
">Close</button>
</div>
`;
}
document.body.appendChild(popup);
// Close button functionality
const closeButton = popup.querySelector("#closePopup");
closeButton.addEventListener("click", () => {
document.body.removeChild(popup);
});
// Hover effect for close button
closeButton.addEventListener("mouseenter", () => {
closeButton.style.background = "#0d5bc1";
});
closeButton.addEventListener("mouseleave", () => {
closeButton.style.background = "#1a73e8";
});
// Close when clicking outside
document.addEventListener("click", function outsideClick(e) {
if (!popup.contains(e.target)) {
document.body.removeChild(popup);
document.removeEventListener("click", outsideClick);
}
});
}
// Function to show explanation popup
function showExplanationPopup(originalText, explanation) {
// Remove loading popup if it exists
const loadingPopup = document.getElementById("translationLoadingPopup");
if (loadingPopup) {
document.body.removeChild(loadingPopup);
}
const popup = document.createElement("div");
popup.className = "hinglish-popup";
popup.style.position = "fixed";
popup.style.zIndex = "9999";
popup.style.borderRadius = "8px";
popup.style.padding = "20px";
popup.style.boxShadow = "0 4px 12px rgba(0,0,0,0.15)";
popup.style.maxWidth = "500px";
popup.style.fontFamily = "Arial, sans-serif";
popup.style.fontSize = "14px";
popup.style.top = "50%";
popup.style.left = "50%";
popup.style.transform = "translate(-50%, -50%)";
// Dark mode detection and styling
if (
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
) {
popup.style.backgroundColor = "#2d2d2d";
popup.style.color = "#ffffff";
popup.style.border = "1px solid #444";
popup.innerHTML = `
<div style="margin-bottom: 15px;">
<div style="font-weight: bold; margin-bottom: 8px; color: #aaa;">Original Text:</div>
<div style="background: #3a3a3a; padding: 12px; border-radius: 6px; margin-bottom: 15px; line-height: 1.5;">${originalText}</div>
<div style="font-weight: bold; margin-bottom: 8px; color: #aaa;">AI Explanation:</div>
<div style="background: #1a3d6d; padding: 12px; border-radius: 6px; margin-bottom: 15px; line-height: 1.5; white-space: pre-wrap; max-height: 300px; overflow-y: auto;">${explanation}</div>
</div>
<div style="text-align: right;">
<button id="closePopup" style="
cursor: pointer;
padding: 8px 16px;
background: #1a73e8;
color: white;
border: none;
border-radius: 4px;
font-size: 14px;
transition: background 0.2s;
">Close</button>
</div>
`;
} else {
popup.style.backgroundColor = "#ffffff";
popup.style.color = "#333333";
popup.style.border = "1px solid #ddd";
popup.innerHTML = `
<div style="margin-bottom: 15px;">
<div style="font-weight: bold; margin-bottom: 8px; color: #666;">Original Text:</div>
<div style="background: #f5f5f5; padding: 12px; border-radius: 6px; margin-bottom: 15px; line-height: 1.5;">${originalText}</div>
<div style="font-weight: bold; margin-bottom: 8px; color: #666;">AI Explanation:</div>
<div style="background: #e8f0fe; padding: 12px; border-radius: 6px; margin-bottom: 15px; line-height: 1.5; white-space: pre-wrap; max-height: 300px; overflow-y: auto;">${explanation}</div>
</div>
<div style="text-align: right;">
<button id="closePopup" style="
cursor: pointer;
padding: 8px 16px;
background: #1a73e8;
color: white;
border: none;
border-radius: 4px;
font-size: 14px;
transition: background 0.2s;
">Close</button>
</div>
`;
}
document.body.appendChild(popup);
// Close button functionality
const closeButton = popup.querySelector("#closePopup");
closeButton.addEventListener("click", () => {
document.body.removeChild(popup);
});
// Hover effect for close button
closeButton.addEventListener("mouseenter", () => {
closeButton.style.background = "#0d5bc1";
});
closeButton.addEventListener("mouseleave", () => {
closeButton.style.background = "#1a73e8";
});
// Close when clicking outside
document.addEventListener("click", function outsideClick(e) {
if (!popup.contains(e.target)) {
document.body.removeChild(popup);
document.removeEventListener("click", outsideClick);
}
});
}
// Function to show error popup
function showErrorPopup(errorMessage) {
// Remove loading popup if it exists
const loadingPopup = document.getElementById("translationLoadingPopup");
if (loadingPopup) {
document.body.removeChild(loadingPopup);
}
const popup = document.createElement("div");
popup.className = "hinglish-popup";
popup.style.position = "fixed";
popup.style.zIndex = "9999";
popup.style.borderRadius = "8px";
popup.style.padding = "20px";
popup.style.boxShadow = "0 4px 12px rgba(0,0,0,0.15)";
popup.style.maxWidth = "300px";
popup.style.fontFamily = "Arial, sans-serif";
popup.style.fontSize = "14px";
popup.style.top = "50%";
popup.style.left = "50%";
popup.style.transform = "translate(-50%, -50%)";
// Dark mode detection and styling
if (
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
) {
popup.style.backgroundColor = "#2d2d2d";
popup.style.color = "#ffffff";
popup.style.border = "1px solid #444";
popup.innerHTML = `
<div style="margin-bottom: 15px;">
<div style="font-weight: bold; margin-bottom: 8px; color: #ff6b6b;">Error:</div>
<div style="margin-bottom: 15px; line-height: 1.5;">${errorMessage}</div>
</div>
<div style="text-align: right;">
<button id="closePopup" style="
cursor: pointer;
padding: 8px 16px;
background: #d93025;
color: white;
border: none;
border-radius: 4px;
font-size: 14px;
transition: background 0.2s;
">Close</button>
</div>
`;
} else {
popup.style.backgroundColor = "#ffffff";
popup.style.color = "#333333";
popup.style.border = "1px solid #ddd";
popup.innerHTML = `
<div style="margin-bottom: 15px;">
<div style="font-weight: bold; margin-bottom: 8px; color: #d93025;">Error:</div>
<div style="margin-bottom: 15px; line-height: 1.5;">${errorMessage}</div>
</div>
<div style="text-align: right;">
<button id="closePopup" style="
cursor: pointer;
padding: 8px 16px;
background: #d93025;
color: white;
border: none;
border-radius: 4px;
font-size: 14px;
transition: background 0.2s;
">Close</button>
</div>
`;
}
document.body.appendChild(popup);
// Close button functionality
const closeButton = popup.querySelector("#closePopup");
closeButton.addEventListener("click", () => {
document.body.removeChild(popup);
});
// Hover effect for close button
closeButton.addEventListener("mouseenter", () => {
closeButton.style.background = "#c5221f";
});
closeButton.addEventListener("mouseleave", () => {
closeButton.style.background = "#d93025";
});
// Auto close after 5 seconds
setTimeout(() => {
if (document.body.contains(popup)) {
document.body.removeChild(popup);
}
}, 5000);
}