-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
1495 lines (1279 loc) · 53.6 KB
/
Copy pathpopup.js
File metadata and controls
1495 lines (1279 loc) · 53.6 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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Utility: safely get element by id
function $(id) {
return document.getElementById(id);
}
// i18n: Load translation files dynamically
let translations = {};
let currentLanguage = 'english';
// Loads the translation JSON for the selected language
async function loadTranslations(lang) {
if (!['english', 'dutch'].includes(lang)) lang = 'english';
let localeFile = lang === 'english' ? 'locales/en.json' : 'locales/nl.json';
try {
const res = await fetch(localeFile);
translations[lang] = await res.json();
} catch (e) {
console.error('Failed to load translations:', localeFile, e);
translations[lang] = {};
}
}
// Centralized translation getter
function getTranslation(key) {
return (translations[currentLanguage] && translations[currentLanguage][key]) || key;
}
// Helper: Get language name in English for prompt suffix
function getLanguageDisplayName(lang) {
switch (lang) {
case 'dutch': return 'Dutch';
// Add more languages as needed
default: return lang.charAt(0).toUpperCase() + lang.slice(1);
}
}
// Helper: Get prompt from EN locale, regardless of current language
function getEnglishPrompt(key) {
if (translations['english'] && translations['english'][key]) {
return translations['english'][key];
}
return key;
}
// Modify prompt before sending to Gemini
function getPromptWithLanguageSuffix(promptKey) {
let prompt = getTranslation(promptKey);
if (currentLanguage !== 'english') {
// Always use the English prompt template, not the translation key value
prompt = getEnglishPrompt(promptKey);
return prompt + ` IMPORTANT: Please use ${getLanguageDisplayName(currentLanguage)} in your response.`;
}
return prompt;
}
// Update all UI elements with translation keys
function updateUILanguage() {
// Title
if ($("title")) $("title").innerText = getTranslation('title');
// Language toggle button
if (languageToggleBtn) languageToggleBtn.innerText = currentLanguage === 'english' ? 'NL' : 'EN';
// Tabs
const tabKeys = ['summarize', 'quiz', 'explain', 'suggest', 'custom'];
tabButtons.forEach((button, idx) => {
const tabKey = tabKeys[idx];
if (tabKey && getTranslation(tabKey)) {
button.textContent = getTranslation(tabKey);
}
});
// Summarize tab
const summarizeH2 = document.querySelector('#summarize h2');
if (summarizeH2) summarizeH2.textContent = getTranslation('summarizeTitle');
const summarizeDescP = document.querySelector('#summarize p');
if (summarizeDescP) summarizeDescP.textContent = getTranslation('summarizeDesc');
const summaryLengthShort = document.querySelector('#summary-length option[value="short"]');
if (summaryLengthShort) summaryLengthShort.textContent = getTranslation('short');
const summaryLengthMedium = document.querySelector('#summary-length option[value="medium"]');
if (summaryLengthMedium) summaryLengthMedium.textContent = getTranslation('medium');
const summaryLengthLong = document.querySelector('#summary-length option[value="long"]');
if (summaryLengthLong) summaryLengthLong.textContent = getTranslation('long');
if (generateSummaryBtn) generateSummaryBtn.textContent = getTranslation('generate');
// Quiz tab
const quizH2 = document.querySelector('#quiz h2');
if (quizH2) quizH2.textContent = getTranslation('quizTitle');
const quizDescP = document.querySelector('#quiz p');
if (quizDescP) quizDescP.textContent = getTranslation('quizDesc');
const questionTypeMultiple = document.querySelector('#question-type option[value="multiple-choice"]');
if (questionTypeMultiple) questionTypeMultiple.textContent = getTranslation('multipleChoice');
const questionTypeTrueFalse = document.querySelector('#question-type option[value="true-false"]');
if (questionTypeTrueFalse) questionTypeTrueFalse.textContent = getTranslation('trueFalse');
const questionTypeShortAnswer = document.querySelector('#question-type option[value="short-answer"]');
if (questionTypeShortAnswer) questionTypeShortAnswer.textContent = getTranslation('shortAnswer');
const questionTypeMixed = document.querySelector('#question-type option[value="mixed"]');
if (questionTypeMixed) questionTypeMixed.textContent = getTranslation('mixed');
const questionCount = document.querySelector('#question-count');
if (questionCount) questionCount.placeholder = getTranslation('questionCount');
const quizDifficulty = document.querySelector('#quiz-difficulty');
if (quizDifficulty) quizDifficulty.placeholder = getTranslation('difficulty');
const quizDifficultyEasy = document.querySelector('#quiz-difficulty option[value="easy"]');
if (quizDifficultyEasy) quizDifficultyEasy.textContent = getTranslation('easy');
const quizDifficultyMedium = document.querySelector('#quiz-difficulty option[value="medium"]');
if (quizDifficultyMedium) quizDifficultyMedium.textContent = getTranslation('medium');
const quizDifficultyHard = document.querySelector('#quiz-difficulty option[value="hard"]');
if (quizDifficultyHard) quizDifficultyHard.textContent = getTranslation('hard');
if (generateQuizBtn) generateQuizBtn.textContent = getTranslation('generate');
// Explain tab
const explainH2 = document.querySelector('#explain h2');
if (explainH2) explainH2.textContent = getTranslation('explainTitle');
const explainDescP = document.querySelector('#explain p');
if (explainDescP) explainDescP.textContent = getTranslation('explainDesc');
const topicInput = document.querySelector('#topic-input');
if (topicInput) topicInput.placeholder = getTranslation('topicPlaceholder');
const explanationLevelBeginner = document.querySelector('#explanation-level option[value="beginner"]');
if (explanationLevelBeginner) explanationLevelBeginner.textContent = getTranslation('beginner');
const explanationLevelIntermediate = document.querySelector('#explanation-level option[value="intermediate"]');
if (explanationLevelIntermediate) explanationLevelIntermediate.textContent = getTranslation('intermediate');
const explanationLevelAdvanced = document.querySelector('#explanation-level option[value="advanced"]');
if (explanationLevelAdvanced) explanationLevelAdvanced.textContent = getTranslation('advanced');
if (generateExplanationBtn) generateExplanationBtn.textContent = getTranslation('explain');
// Suggest tab
const suggestH2 = document.querySelector('#suggest h2');
if (suggestH2) suggestH2.textContent = getTranslation('suggestTitle');
const suggestDescP = document.querySelector('#suggest p');
if (suggestDescP) suggestDescP.textContent = getTranslation('suggestDesc');
const teachingFormatLecture = document.querySelector('#teaching-format option[value="lecture"]');
if (teachingFormatLecture) teachingFormatLecture.textContent = getTranslation('lecture');
const teachingFormatDiscussion = document.querySelector('#teaching-format option[value="discussion"]');
if (teachingFormatDiscussion) teachingFormatDiscussion.textContent = getTranslation('discussion');
const teachingFormatActivity = document.querySelector('#teaching-format option[value="activity"]');
if (teachingFormatActivity) teachingFormatActivity.textContent = getTranslation('activity');
const teachingFormatAssessment = document.querySelector('#teaching-format option[value="assessment"]');
if (teachingFormatAssessment) teachingFormatAssessment.textContent = getTranslation('assessment');
if (generateSuggestionsBtn) generateSuggestionsBtn.textContent = getTranslation('getSuggestions');
// Loading
const loadingP = document.querySelector('#loading p');
if (loadingP) loadingP.textContent = getTranslation('processing');
// Result actions
if (copyResultBtn) copyResultBtn.textContent = getTranslation('copy');
if (exportPdfBtn) exportPdfBtn.textContent = getTranslation('exportPdf');
// Footer
const footerP = document.querySelector('footer p');
if (footerP) footerP.textContent = getTranslation('footer');
// Custom tab
const customH2 = document.querySelector('#custom h2');
if (customH2) customH2.textContent = getTranslation('customTitle');
const customDescP = document.querySelector('#custom p');
if (customDescP) customDescP.textContent = getTranslation('customDesc');
const customPromptInput = document.querySelector('#custom-prompt');
if (customPromptInput) customPromptInput.placeholder = getTranslation('customPlaceholder');
if (generateCustomBtn) generateCustomBtn.textContent = getTranslation('ask');
const templateLabel = document.querySelector('.template-label');
if (templateLabel) templateLabel.textContent = getTranslation('templateLabel');
// Update template button texts
const templateMainArgsBtn = document.querySelector('.template-btn[data-prompt="What are the main arguments presented in this text?"]');
if (templateMainArgsBtn) templateMainArgsBtn.textContent = getTranslation('templateMainArgs');
const templateConceptMapBtn = document.querySelector('.template-btn[data-prompt="Create a concept map based on this content."]');
if (templateConceptMapBtn) templateConceptMapBtn.textContent = getTranslation('templateConceptMap');
const templateImplicationsBtn = document.querySelector('.template-btn[data-prompt="What are the implications of this content for students?"]');
if (templateImplicationsBtn) templateImplicationsBtn.textContent = getTranslation('templateImplications');
const templateBiasAnalysisBtn = document.querySelector('.template-btn[data-prompt="Identify any biases or limitations in this content."]');
if (templateBiasAnalysisBtn) templateBiasAnalysisBtn.textContent = getTranslation('templateBiasAnalysis');
const templateLearningStylesBtn = document.querySelector('.template-btn[data-prompt="How could I adapt this content for different learning styles?"]');
if (templateLearningStylesBtn) templateLearningStylesBtn.textContent = getTranslation('templateLearningStyles');
const templateReflectionQuestionsBtn = document.querySelector('.template-btn[data-prompt="Create 3 reflection questions for students after studying this content."]');
if (templateReflectionQuestionsBtn) templateReflectionQuestionsBtn.textContent = getTranslation('templateReflectionQuestions');
// Update tooltips
updateTooltips();
}
// Language switch handler
async function switchLanguage(lang) {
if (!translations[lang]) await loadTranslations(lang);
currentLanguage = lang;
updateUILanguage();
// Persist language choice in both chrome.storage.local and localStorage for compatibility
const chromeLang = lang === 'dutch' ? 'nl' : 'en';
chrome.storage.local.set({ language: chromeLang });
localStorage.setItem('vu_educationlab_extension_language', lang);
}
// Authentication check and UI management
async function checkAuthenticationAndShowUI() {
console.log('🔄 checkAuthenticationAndShowUI called');
const authSection = document.getElementById('auth-section');
const featuresSection = document.getElementById('features-section');
try {
// First check if user has stored auth data
const isAuth = await window.VUAuth.isAuthenticated();
console.log('🔐 Authentication status:', isAuth);
if (isAuth) {
// User has stored auth - try to get a valid token (will refresh if needed)
console.log('✅ User has stored auth - validating token...');
const token = await window.VUAuth.getValidToken();
if (token) {
// Token is valid - show features
console.log('✅ Token valid - showing features');
authSection.style.display = 'none';
if (featuresSection) {
featuresSection.classList.remove('hidden');
featuresSection.style.display = 'block';
}
} else {
// Token refresh failed - user needs to sign in again
console.log('❌ Token expired/invalid - showing auth section');
authSection.style.display = 'block';
featuresSection.classList.add('hidden');
}
} else {
// User is not authenticated - show auth section
console.log('❌ User not authenticated - showing auth section');
authSection.style.display = 'block';
featuresSection.classList.add('hidden');
}
} catch (error) {
console.error('❌ Error checking authentication:', error);
// On error, show auth section
authSection.style.display = 'block';
featuresSection.classList.add('hidden');
}
}
// On DOMContentLoaded, load default or saved language
document.addEventListener('DOMContentLoaded', async () => {
// Get DOM elements
featuresSection = document.getElementById('features-section');
tabButtons = document.querySelectorAll('.tab-btn');
tabPanes = document.querySelectorAll('.tab-pane');
resultContainer = document.getElementById('result-container');
resultContent = document.getElementById('result-content');
loadingIndicator = document.getElementById('loading');
resultActions = document.querySelector('.result-actions');
expandToggle = document.getElementById('expand-toggle');
resultFade = document.getElementById('result-fade');
copyResultBtn = document.getElementById('copy-result');
exportPdfBtn = document.getElementById('export-pdf');
if (expandToggle) {
expandToggle.addEventListener('click', toggleResultExpand);
}
generateSummaryBtn = document.getElementById('generate-summary');
generateQuizBtn = document.getElementById('generate-quiz');
generateExplanationBtn = document.getElementById('generate-explanation');
generateSuggestionsBtn = document.getElementById('generate-suggestions');
languageToggleBtn = document.getElementById('language-toggle-btn');
settingsBtn = document.getElementById('settings-btn');
generateCustomBtn = document.getElementById('generate-custom');
customPromptInput = document.getElementById('custom-prompt');
templateButtons = document.querySelectorAll('.template-btn');
// Settings button navigation
if (settingsBtn) {
settingsBtn.addEventListener('click', () => {
window.location.href = 'settings.html';
});
}
// Language: load saved or default
chrome.storage.local.get(['language'], async (result) => {
let savedLang = result.language;
if (!savedLang) {
savedLang = localStorage.getItem('vu_educationlab_extension_language');
}
currentLanguage = savedLang === 'nl' ? 'dutch' : 'english';
await loadTranslations('english');
await loadTranslations('dutch');
updateUILanguage();
});
// Tab switching
tabButtons.forEach(button => {
button.addEventListener('click', () => {
addButtonClickEffect(button);
switchTab(button.dataset.tab);
});
});
// Feature buttons with click effects
generateSummaryBtn.addEventListener('click', () => {
addButtonClickEffect(generateSummaryBtn);
generateSummary();
});
generateQuizBtn.addEventListener('click', () => {
addButtonClickEffect(generateQuizBtn);
generateQuiz();
});
generateExplanationBtn.addEventListener('click', () => {
addButtonClickEffect(generateExplanationBtn);
generateExplanation();
});
generateSuggestionsBtn.addEventListener('click', () => {
addButtonClickEffect(generateSuggestionsBtn);
generateSuggestions();
});
// Result actions
copyResultBtn.addEventListener('click', () => {
addButtonClickEffect(copyResultBtn);
copyResult();
});
exportPdfBtn.addEventListener('click', () => {
addButtonClickEffect(exportPdfBtn);
exportToPDF();
});
// Keyboard navigation
document.addEventListener('keydown', handleKeyboardNavigation);
// Add template button event listeners
templateButtons.forEach(button => {
button.addEventListener('click', () => {
// Get the appropriate prompt based on current language
const promptKey = currentLanguage === 'english' ? 'data-prompt' : 'data-prompt-nl';
const promptText = button.getAttribute(promptKey);
if (promptText) {
customPromptInput.value = promptText;
// Focus on the textarea after setting the value
customPromptInput.focus();
}
// Add visual feedback
addButtonClickEffect(button);
});
});
generateCustomBtn.addEventListener('click', () => {
addButtonClickEffect(generateCustomBtn);
generateCustomResponse();
});
// Custom prompt keyboard shortcut
customPromptInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && e.ctrlKey) {
generateCustomResponse();
}
});
// Update tooltips based on current language
updateTooltips();
// Setup authentication event listeners
const signInBtn = document.getElementById('sign-in-btn');
const authError = document.getElementById('auth-error');
if (signInBtn) {
signInBtn.addEventListener('click', async () => {
try {
signInBtn.disabled = true;
signInBtn.textContent = 'Signing in...';
authError.style.display = 'none';
console.log('🔐 Starting sign-in process...');
await window.VUAuth.signIn();
console.log('✅ Sign-in completed, refreshing UI...');
// Show success feedback
signInBtn.textContent = '✅ Signed in!';
signInBtn.style.background = 'linear-gradient(135deg, #4CAF50 0%, #45a049 100%)';
// Small delay to ensure storage write completes
await new Promise(resolve => setTimeout(resolve, 200));
// Refresh UI after successful sign in
await checkAuthenticationAndShowUI();
console.log('✅ UI refresh complete');
// If we got here, sign-in was successful
// The auth section should now be hidden and features should be visible
} catch (error) {
console.error('❌ Sign in error:', error);
authError.textContent = error.message || 'Sign in failed. Please try again.';
authError.style.display = 'block';
signInBtn.disabled = false;
signInBtn.innerHTML = '<img src="https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg" alt="Google" style="width: 18px; height: 18px; margin-right: 8px;">Sign in with Google';
}
});
}
// Check authentication status on load
await checkAuthenticationAndShowUI();
// Listen for storage changes (e.g., when auth completes)
chrome.storage.onChanged.addListener((changes, namespace) => {
if (namespace === 'local' && changes.vuAuthUser) {
console.log('🔄 Auth state changed, refreshing UI...');
checkAuthenticationAndShowUI();
}
});
});
// Handle keyboard navigation
function handleKeyboardNavigation(e) {
// Tab navigation with arrow keys when tabs are focused
if (document.activeElement.classList.contains('tab-btn')) {
if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
e.preventDefault();
const activeTabIndex = Array.from(tabButtons).findIndex(btn =>
btn.classList.contains('active')
);
let newIndex;
if (e.key === 'ArrowRight') {
newIndex = (activeTabIndex + 1) % tabButtons.length;
} else {
newIndex = (activeTabIndex - 1 + tabButtons.length) % tabButtons.length;
}
tabButtons[newIndex].click();
tabButtons[newIndex].focus();
}
}
// Use Escape to clear status messages
if (e.key === 'Escape') {
if (apiStatus.textContent) {
setTimeout(() => {
apiStatus.textContent = '';
apiStatus.className = '';
}, 200);
}
}
}
// Add visual click effect to buttons
function addButtonClickEffect(button) {
button.classList.add('button-click');
setTimeout(() => {
button.classList.remove('button-click');
}, 300);
}
// Get current tab content
async function getCurrentTabContent() {
return new Promise((resolve) => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const activeTab = tabs[0];
chrome.tabs.sendMessage(
activeTab.id,
{ action: "getPageContent" },
(response) => {
if (response && response.content) {
resolve(response.content);
} else {
// If content script hasn't responded, try using the background script
chrome.runtime.sendMessage(
{
action: "getPageContent",
tabId: activeTab.id
},
(response) => {
resolve(response ? response.content : {
title: activeTab.title,
url: activeTab.url,
text: "Could not extract page content."
});
}
);
}
}
);
});
});
}
// Helper function to check if page content extraction failed (PDF or minimal content)
function checkContentExtractionIssues(pageContent) {
// Check for PDF extraction failure
if (pageContent.isPDF && pageContent.pdfExtractionFailed) {
return {
hasIssue: true,
isPDF: true,
message: 'pdf_extraction_failed'
};
}
// Check for minimal content (likely a PDF or embedded content)
const paragraphCount = pageContent.paragraphs?.length || 0;
const headingCount = (pageContent.headings?.h1?.length || 0) +
(pageContent.headings?.h2?.length || 0) +
(pageContent.headings?.h3?.length || 0);
const textLength = pageContent.text?.length || 0;
const totalContent = paragraphCount + headingCount;
// If very little content detected and URL suggests it might be a PDF
const urlLooksLikePDF = pageContent.url?.toLowerCase().includes('.pdf') ||
pageContent.title?.toLowerCase().includes('.pdf');
if (totalContent < 3 && textLength < 200) {
return {
hasIssue: true,
isPDF: urlLooksLikePDF,
message: urlLooksLikePDF ? 'pdf_extraction_failed' : 'minimal_content'
};
}
return { hasIssue: false };
}
// Display PDF extraction error message
function displayPDFExtractionError() {
hideLoading();
const title = getTranslation('pdfExtractionFailedTitle');
const message = getTranslation('pdfExtractionFailedMessage');
const solutions = getTranslation('pdfExtractionFailedSolutions');
const option1 = getTranslation('pdfExtractionFailedOption1');
const option2 = getTranslation('pdfExtractionFailedOption2');
const option3 = getTranslation('pdfExtractionFailedOption3');
const option4 = getTranslation('pdfExtractionFailedOption4');
resultContent.innerHTML = `
<div class="pdf-error-message" style="padding: 15px;">
<h3 style="color: #d32f2f; margin-bottom: 12px; display: flex; align-items: center; gap: 8px;">
<span style="font-size: 24px;">📄</span> ${title}
</h3>
<p style="margin-bottom: 15px; line-height: 1.6;">${message}</p>
<p style="margin-bottom: 10px; font-weight: 600;">${solutions}</p>
<ul style="margin-left: 20px; line-height: 1.8;">
<li>🌐 ${option1}</li>
<li>📖 ${option2}</li>
<li>📋 ${option3}</li>
<li>🎓 ${option4}</li>
</ul>
</div>
`;
resultContent.style.opacity = '1';
resultActions.classList.add('hidden');
resultContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
// Display minimal content warning message
function displayMinimalContentWarning() {
hideLoading();
const message = getTranslation('minimalContentWarning');
resultContent.innerHTML = `
<div class="minimal-content-warning" style="padding: 15px;">
<h3 style="color: #f57c00; margin-bottom: 12px; display: flex; align-items: center; gap: 8px;">
<span style="font-size: 24px;">⚠️</span> ${currentLanguage === 'english' ? 'Limited Content Detected' : 'Beperkte Inhoud Gedetecteerd'}
</h3>
<p style="margin-bottom: 15px; line-height: 1.6;">${message}</p>
<p style="line-height: 1.6;">
${currentLanguage === 'english'
? 'Try refreshing the page or wait for it to fully load before trying again.'
: 'Probeer de pagina te vernieuwen of wacht tot deze volledig is geladen voordat u het opnieuw probeert.'}
</p>
</div>
`;
resultContent.style.opacity = '1';
resultActions.classList.add('hidden');
resultContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
// Helper function to create structured content from page content
function createStructuredContent(pageContent) {
let structuredContent = `Title: ${pageContent.title}\n`;
if (pageContent.metaDescription) {
structuredContent += `Description: ${pageContent.metaDescription}\n`;
}
if (pageContent.headings && pageContent.headings.h1 && pageContent.headings.h1.length > 0) {
structuredContent += `Main Headings: ${pageContent.headings.h1.join(', ')}\n`;
}
if (pageContent.paragraphs && pageContent.paragraphs.length > 0) {
structuredContent += `\nContent:\n${pageContent.paragraphs.join('\n\n')}\n`;
} else {
structuredContent += `\nContent:\n${pageContent.text}\n`;
}
// Include lists if available
if (pageContent.lists && pageContent.lists.length > 0) {
structuredContent += `\nLists:\n`;
pageContent.lists.forEach(list => {
structuredContent += `${list.type.toUpperCase()}:\n`;
list.items.forEach((item, index) => {
structuredContent += `${index + 1}. ${item}\n`;
});
structuredContent += `\n`;
});
}
return structuredContent;
}
// Generate summary of current page
async function generateSummary() {
showLoading();
const summaryLengthOption = document.getElementById('summary-length').value;
const pageContent = await getCurrentTabContent();
// Check for PDF extraction failure or minimal content
const contentIssue = checkContentExtractionIssues(pageContent);
if (contentIssue.hasIssue) {
if (contentIssue.isPDF) {
displayPDFExtractionError();
} else {
displayMinimalContentWarning();
}
return;
}
// Create a more structured prompt using the enhanced content extraction
const structuredContent = createStructuredContent(pageContent);
const prompt = getPromptWithLanguageSuffix('summaryPrompt')
.replace('{length}', summaryLengthOption)
.replace('{content}', structuredContent);
const maxTokensByLength = { short: 500, medium: 1500, long: 4000 };
callGemini(prompt, 'summarize', { maxTokens: maxTokensByLength[summaryLengthOption] || 1500 });
// Highlight key terms on the page
highlightKeyTerms();
}
// Generate quiz questions from current page
async function generateQuiz() {
showLoading();
const questionType = document.getElementById('question-type').value;
const questionCount = document.getElementById('question-count').value;
const quizDifficulty = document.getElementById('quiz-difficulty').value;
const pageContent = await getCurrentTabContent();
// Check for PDF extraction failure or minimal content
const contentIssue = checkContentExtractionIssues(pageContent);
if (contentIssue.hasIssue) {
if (contentIssue.isPDF) {
displayPDFExtractionError();
} else {
displayMinimalContentWarning();
}
return;
}
// Create a more structured prompt using the enhanced content extraction
const structuredContent = createStructuredContent(pageContent);
const quizOptions = getQuizOptions();
const prompt = getPromptWithLanguageSuffix('quizPrompt')
.replace('{count}', questionCount)
.replace('{type}', questionType)
.replace('{difficulty}', quizDifficulty)
.replace('{level}', quizOptions.level)
.replace('{content}', structuredContent);
callGemini(prompt, 'quiz');
}
// Helper function to get quiz options
function getQuizOptions() {
const type = document.getElementById('question-type').value;
const difficulty = document.getElementById('quiz-difficulty').value;
const level = 'university';
return { type, difficulty, level };
}
// Generate explanation of complex topics
async function generateExplanation() {
showLoading();
const topic = document.getElementById('topic-input').value;
const level = document.getElementById('explanation-level').value;
const pageContent = await getCurrentTabContent();
// Check for PDF extraction failure or minimal content
const contentIssue = checkContentExtractionIssues(pageContent);
if (contentIssue.hasIssue) {
if (contentIssue.isPDF) {
displayPDFExtractionError();
} else {
displayMinimalContentWarning();
}
return;
}
// Create a more structured prompt using the enhanced content extraction
const structuredContent = createStructuredContent(pageContent);
let prompt;
if (topic) {
prompt = getPromptWithLanguageSuffix('explainTopicPrompt')
.replace('{topic}', topic)
.replace('{level}', level)
.replace('{content}', structuredContent);
} else {
prompt = getPromptWithLanguageSuffix('explainGeneralPrompt')
.replace('{level}', level)
.replace('{content}', structuredContent);
}
callGemini(prompt, 'explain');
// If a specific topic was provided, highlight it on the page
if (topic) {
highlightSpecificTerm(topic);
}
}
// Generate teaching suggestions
async function generateSuggestions() {
showLoading();
const format = document.getElementById('teaching-format').value;
const pageContent = await getCurrentTabContent();
// Check for PDF extraction failure or minimal content
const contentIssue = checkContentExtractionIssues(pageContent);
if (contentIssue.hasIssue) {
if (contentIssue.isPDF) {
displayPDFExtractionError();
} else {
displayMinimalContentWarning();
}
return;
}
// Create a more structured prompt using the enhanced content extraction
const structuredContent = createStructuredContent(pageContent);
// Use the appropriate prompt based on the format
let prompt;
if (format === 'essay') {
prompt = getPromptWithLanguageSuffix('essayPrompt')
.replace('{content}', structuredContent);
} else {
prompt = getPromptWithLanguageSuffix('suggestPrompt')
.replace('{format}', format)
.replace('{content}', structuredContent);
}
callGemini(prompt, 'suggest');
}
// Send highlight request to content script
function sendHighlightRequest(action, text = null) {
try {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const activeTab = tabs[0];
chrome.tabs.sendMessage(
activeTab.id,
{
action: action,
...(text && { text })
}
);
});
} catch (error) {
console.error(`Error with highlight request (${action}):`, error);
}
}
// Highlight key terms on the page
async function highlightKeyTerms() {
sendHighlightRequest("clearHighlights");
}
// Highlight specific term on the page
async function highlightSpecificTerm(term) {
if (!term) return;
sendHighlightRequest("highlightText", term);
}
// Call Backend API with streaming support
async function callGemini(prompt, feature, extraOptions = {}) {
let streamCleanup = null;
try {
// Prepare system prompt based on feature
let systemPrompt;
switch (feature) {
case 'summarize':
systemPrompt = getTranslation('summarizeSystemPrompt');
break;
case 'quiz':
systemPrompt = getTranslation('quizSystemPrompt');
break;
case 'explain':
systemPrompt = getTranslation('explainSystemPrompt');
break;
case 'suggest':
systemPrompt = getTranslation('suggestSystemPrompt');
break;
case 'custom':
systemPrompt = getTranslation('customSystemPrompt');
break;
}
// Set up for streaming display
hideLoading();
resetExpandState();
resultContent.innerHTML = '';
resultContent.style.opacity = '1';
resultActions.classList.add('hidden');
let accumulatedText = '';
let userHasScrolled = false;
let overflowCheckTimer = null;
const onUserScroll = () => { userHasScrolled = true; };
resultContainer.addEventListener('wheel', onUserScroll, { passive: true });
resultContainer.addEventListener('touchmove', onUserScroll, { passive: true });
streamCleanup = () => {
resultContainer.removeEventListener('wheel', onUserScroll);
resultContainer.removeEventListener('touchmove', onUserScroll);
if (overflowCheckTimer) clearTimeout(overflowCheckTimer);
checkResultOverflow();
};
// Scroll the container into view once at the start
resultContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
const options = {
systemPrompt: systemPrompt,
feature: feature,
maxTokens: extraOptions.maxTokens || null,
onChunk: (chunk) => {
accumulatedText += chunk;
const formattedText = convertMarkdownToHTML(accumulatedText);
resultContent.innerHTML = formattedText;
if (!userHasScrolled) {
resultContainer.scrollTop = resultContainer.scrollHeight;
}
if (!overflowCheckTimer) {
overflowCheckTimer = setTimeout(() => {
checkResultOverflow();
overflowCheckTimer = null;
}, 500);
}
}
};
const response = await window.GeminiAPI.generateContent(prompt, options);
streamCleanup();
displayResult(response);
} catch (error) {
hideLoading();
if (streamCleanup) streamCleanup();
// Check if it's an authentication error
if (error.message.includes('Authentication') || error.message.includes('sign in')) {
resultContent.innerHTML = `
<div style="text-align: center; padding: 20px;">
<h3 style="color: #d32f2f; margin-bottom: 10px;">Authentication Required</h3>
<p style="margin-bottom: 15px;">${error.message}</p>
<button id="retry-auth-btn" style="
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 10px 20px;
border-radius: 8px;
cursor: pointer;
font-size: 14px;
font-weight: 600;
">Sign In Again</button>
</div>
`;
// Add event listener to the button
const retryBtn = document.getElementById('retry-auth-btn');
if (retryBtn) {
retryBtn.addEventListener('click', async () => {
try {
retryBtn.textContent = 'Signing in...';
retryBtn.disabled = true;
await window.VUAuth.signIn();
await checkAuthenticationAndShowUI();
} catch (signInError) {
console.error('Sign in error:', signInError);
alert(signInError.message || 'Sign in failed. Please try again.');
retryBtn.textContent = 'Sign In Again';
retryBtn.disabled = false;
}
});
}
} else {
resultContent.textContent = `Error: ${error.message}`;
}
resultContent.classList.add('error-text');
console.error('Backend API Error:', error);
shakeElement(resultContainer);
setTimeout(() => {
resultContent.classList.remove('error-text');
}, 2000);
}
}
// Check if the result container content overflows and show/hide the expand toggle
function checkResultOverflow() {
if (!resultContainer || !expandToggle || !resultFade) return;
const isOverflowing = resultContainer.scrollHeight > resultContainer.clientHeight + 10;
const isExpanded = resultContainer.classList.contains('expanded');
if (isOverflowing && !isExpanded) {
expandToggle.classList.remove('hidden');
resultFade.classList.remove('hidden');
} else {
if (!isExpanded) {
expandToggle.classList.add('hidden');
}
resultFade.classList.add('hidden');
}
}
function toggleResultExpand() {
if (!resultContainer || !expandToggle || !resultFade) return;
const isExpanded = resultContainer.classList.toggle('expanded');
if (isExpanded) {
expandToggle.textContent = getTranslation('showLess');
resultFade.classList.add('hidden');
} else {
expandToggle.textContent = getTranslation('showMore');
resultContainer.scrollTop = 0;
checkResultOverflow();
}
}
function resetExpandState() {
if (!resultContainer || !expandToggle || !resultFade) return;
resultContainer.classList.remove('expanded');
expandToggle.classList.add('hidden');
expandToggle.textContent = getTranslation('showMore');
resultFade.classList.add('hidden');
}
// Display API response with markdown formatting
function displayResult(text) {
hideLoading();
resetExpandState();
// Add animation for result appearance
resultContent.style.opacity = '0';
// Convert markdown to HTML using simple regex replacements
const formattedText = convertMarkdownToHTML(text);
// Use innerHTML to render the formatted HTML
resultContent.innerHTML = formattedText;
setTimeout(() => {
resultContent.style.opacity = '1';
// Smooth scroll to results
resultContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
// Check if content overflows and show expand toggle
checkResultOverflow();
// Show action buttons with animation
setTimeout(() => {
resultActions.classList.remove('hidden');
resultActions.style.opacity = '0';
resultActions.style.transform = 'translateY(10px)';
setTimeout(() => {
resultActions.style.opacity = '1';
resultActions.style.transform = 'translateY(0)';