-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpopup.js
More file actions
1459 lines (1245 loc) · 46.5 KB
/
popup.js
File metadata and controls
1459 lines (1245 loc) · 46.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
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
let settings = {
enabled: true,
autoQuiz: true,
questionCount: 1,
finalQuizEnabled: true,
soundEnabled: true,
theme: 'light',
themeScope: 'quiz-popup',
analyticsEnabled: true,
aiProvider: 'on-device',
geminiApiKey: '',
modelProviderExpanded: false
};
const STATUS_LABELS = {
completed: 'Completed',
ready: 'Ready',
processing: 'Processing',
pending: 'Pending',
error: 'Failed',
skipped: 'Skipped',
idle: 'Idle'
};
const modelStates = {
languageModel: { status: 'checking', message: 'Checking...', canDownload: false },
summarizer: { status: 'checking', message: 'Checking...', canDownload: false }
};
let downloadInProgress = false;
const downloadModelsBtn = document.getElementById('downloadModels');
const downloadModelsHelp = document.getElementById('downloadModelsHelp');
function isMissingContentScriptError(error) {
const message = (error?.message || '').toLowerCase();
if (!message) return false;
return message.includes('could not establish connection') ||
message.includes('receiving end does not exist') ||
message.includes('message port closed before a response') ||
message.includes('the message channel closed');
}
async function ensureContentScript(tabId) {
if (!tabId || !chrome?.scripting) {
return false;
}
try {
await chrome.scripting.insertCSS({
target: { tabId },
files: ['content.css']
});
} catch (_cssError) {
// Ignore style injection failures since styles may already exist or the page may block them.
}
try {
await chrome.scripting.executeScript({
target: { tabId },
files: ['content.js']
});
return true;
} catch (scriptError) {
console.warn('LearnTube: Failed to inject content script:', scriptError);
return false;
}
}
async function sendMessageToTab(tabId, message, options) {
try {
return await chrome.tabs.sendMessage(tabId, message, options);
} catch (error) {
if (isMissingContentScriptError(error)) {
const injected = await ensureContentScript(tabId);
if (injected) {
return chrome.tabs.sendMessage(tabId, message, options);
}
}
throw error;
}
}
function isYouTubeWatchUrl(url) {
return typeof url === 'string' && url.includes('youtube.com/watch');
}
async function getActiveTab() {
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
return tab || null;
} catch (error) {
console.error('LearnTube: Failed to query active tab:', error);
return null;
}
}
async function getActiveYouTubeTab() {
const tab = await getActiveTab();
if (tab && isYouTubeWatchUrl(tab.url)) {
return tab;
}
return null;
}
function normalizeModelState(state) {
return {
status: state?.status || 'not-ready',
message: state?.message || '',
canDownload: Boolean(state?.canDownload)
};
}
function applyModelStates(languageState, summarizerState) {
const normalizedLanguage = normalizeModelState(languageState);
const normalizedSummarizer = normalizeModelState(summarizerState);
setModelState('languageModel', normalizedLanguage);
setModelState('summarizer', normalizedSummarizer);
updateModelStatus('languageModelStatus', normalizedLanguage.status, normalizedLanguage.message, normalizedLanguage.canDownload);
updateModelStatus('summarizerStatus', normalizedSummarizer.status, normalizedSummarizer.message, normalizedSummarizer.canDownload);
updateDownloadModelsBtn();
}
function applyUnavailableModelStates(message) {
const fallbackMessage = message || 'Refresh the YT tab to load LearnTube AI';
const unavailableState = {
status: 'not-ready',
message: fallbackMessage,
canDownload: false
};
applyModelStates(unavailableState, unavailableState);
}
function escapeHtml(value) {
if (value === null || value === undefined) return '';
return String(value).replace(/[&<>"']/g, (char) => {
switch (char) {
case '&': return '&';
case '<': return '<';
case '>': return '>';
case '"': return '"';
case "'": return ''';
default: return char;
}
});
}
function classForStatus(rawStatus) {
const status = (rawStatus || '').toString().toLowerCase();
if (status === 'completed' || status === 'ready') return 'status-pill status-completed';
if (status === 'processing' || status === 'in-progress') return 'status-pill status-processing';
if (status === 'error' || status === 'failed') return 'status-pill status-error';
if (status === 'skipped') return 'status-pill status-skipped';
return 'status-pill status-pending';
}
function labelForStatus(rawStatus) {
const status = (rawStatus || '').toString().toLowerCase();
return STATUS_LABELS[status] || STATUS_LABELS.pending;
}
function deriveOverallStatus(status) {
if (!status) return 'pending';
const overall = (status.overallStatus || '').toString().toLowerCase();
if (overall) return overall;
const finalStatus = (status.final?.status || '').toString().toLowerCase();
if (finalStatus === 'error') return 'error';
return 'processing';
}
function updateStatusSummary(state = 'pending', labelOverride) {
const pill = document.getElementById('statusSummaryPill');
if (!pill) return;
const normalized = (state || 'pending').toString().toLowerCase();
pill.className = classForStatus(normalized);
pill.textContent = labelOverride ? labelOverride : labelForStatus(normalized);
}
function setModelState(modelType, state) {
if (!modelType || !modelStates[modelType]) {
return;
}
modelStates[modelType] = {
status: (state?.status || 'not-ready'),
message: state?.message || '',
canDownload: Boolean(state?.canDownload)
};
}
function updateDownloadModelsBtn() {
if (!downloadModelsBtn) {
return;
}
const languageState = modelStates.languageModel || {};
const summarizerState = modelStates.summarizer || {};
const needsDownload = [languageState, summarizerState].some(state => state?.status === 'not-ready' && state?.canDownload);
const hadFailure = [languageState, summarizerState].some(state => (state?.message || '').toLowerCase().includes('failed'));
if (downloadInProgress) {
downloadModelsBtn.style.display = 'block';
downloadModelsBtn.disabled = true;
const currentLabel = (downloadModelsBtn.textContent || '').toLowerCase();
if (!currentLabel.includes('download')) {
downloadModelsBtn.textContent = 'Downloading...';
}
} else if (needsDownload) {
downloadModelsBtn.style.display = 'block';
downloadModelsBtn.disabled = false;
downloadModelsBtn.textContent = hadFailure ? 'Try Again' : 'Download AI Models';
} else {
downloadModelsBtn.style.display = 'none';
}
if (downloadModelsHelp) {
downloadModelsHelp.style.display = (downloadInProgress || needsDownload) ? 'block' : 'none';
}
}
const statusSectionEl = document.getElementById('statusSection');
const statusToggleBtn = document.getElementById('statusToggle');
const statusContentEl = document.getElementById('statusContent');
if (statusContentEl) {
const initiallyCollapsed = statusSectionEl?.classList.contains('collapsed');
statusContentEl.setAttribute('aria-hidden', initiallyCollapsed ? 'true' : 'false');
}
if (statusToggleBtn && statusSectionEl) {
statusToggleBtn.addEventListener('click', () => {
const expanded = statusToggleBtn.getAttribute('aria-expanded') === 'true';
statusToggleBtn.setAttribute('aria-expanded', String(!expanded));
statusSectionEl.classList.toggle('collapsed', expanded);
if (statusContentEl) {
statusContentEl.setAttribute('aria-hidden', expanded ? 'true' : 'false');
}
});
}
function formatRelativeTime(timestamp) {
if (!timestamp && timestamp !== 0) return 'Just now';
const tsNumber = Number(timestamp);
if (!Number.isFinite(tsNumber)) return 'Just now';
const diff = Date.now() - tsNumber;
if (diff < 60000) return 'Just now';
if (diff < 3600000) {
const minutes = Math.round(diff / 60000);
return `${minutes} min${minutes === 1 ? '' : 's'} ago`;
}
if (diff < 86400000) {
const hours = Math.round(diff / 3600000);
return `${hours} hour${hours === 1 ? '' : 's'} ago`;
}
const date = new Date(tsNumber);
return Number.isFinite(date.getTime())
? date.toLocaleDateString([], { month: 'short', day: 'numeric' })
: 'Earlier';
}
function renderCurrentStatus(status) {
const videoTitle = escapeHtml(status?.videoTitle || 'Current video');
const segments = Array.isArray(status?.segments) ? status.segments : [];
let completed = 0;
let processing = 0;
let pending = 0;
let errors = 0;
const errorMessages = [];
segments.forEach(segment => {
const segStatus = (segment?.status || '').toLowerCase();
if (segStatus === 'completed' || segStatus === 'ready') {
completed += 1;
} else if (segStatus === 'processing') {
processing += 1;
} else if (segStatus === 'error') {
errors += 1;
if (segment?.message) {
const index = typeof segment.index === 'number' ? segment.index + 1 : '?';
errorMessages.push(`Segment ${index}: ${segment.message}`);
}
} else {
pending += 1;
}
});
const metrics = [
{ label: 'Total segments', value: segments.length },
{ label: 'Completed', value: completed },
{ label: 'Processing', value: processing },
{ label: 'Pending', value: pending }
];
if (errors > 0) {
metrics.push({ label: 'Failed', value: errors });
}
const totalSegments = segments.length;
const progressPercent = totalSegments ? Math.round((completed / totalSegments) * 100) : 0;
const progressLabel = totalSegments
? `${completed}/${totalSegments} segments ready`
: 'Waiting for first quiz';
const metricsMarkup = totalSegments
? `<div class="status-metrics">${metrics.map(metric => `
<div class="status-metric">
<div class="status-metric-label">${escapeHtml(metric.label)}</div>
<div class="status-metric-value">${escapeHtml(String(metric.value))}</div>
</div>
`).join('')}</div>`
: '';
const progressMarkup = totalSegments
? `
<div class="status-progress">
<div class="status-progress-label">
<span>Segment progress</span>
<span>${progressPercent}%</span>
</div>
<div class="status-progress-bar">
<div class="status-progress-fill" style="width:${progressPercent}%"></div>
</div>
<div class="status-progress-helper">${escapeHtml(progressLabel)}</div>
</div>
`.trim()
: `
<div class="status-progress waiting">
<div class="status-progress-label">
<span>Segment progress</span>
<span>—</span>
</div>
<div class="status-progress-helper">${escapeHtml(progressLabel)}</div>
</div>
`.trim();
const finalStatusObj = status?.final || {};
const finalStatus = (finalStatusObj.status || 'skipped').toLowerCase();
const finalBadge = `<span class="${classForStatus(finalStatus)}">${labelForStatus(finalStatus)}</span>`;
if (finalStatusObj.message && finalStatus === 'error') {
errorMessages.push(`Final quiz: ${finalStatusObj.message}`);
}
const finalNote = (() => {
switch (finalStatus) {
case 'completed':
return 'Ready';
case 'processing':
return 'Generating…';
case 'pending':
return 'Waiting to start';
case 'error':
return 'Needs attention';
case 'skipped':
return 'Disabled';
default:
return '';
}
})();
const finalNoteStatus = ['completed', 'processing', 'pending', 'error', 'skipped'].includes(finalStatus)
? finalStatus
: 'pending';
const finalNoteText = finalNote || 'Status unknown';
const finalContainerClass = `status-final status-final-${finalNoteStatus}`;
const finalNoteClass = `status-final-note status-final-note-${finalNoteStatus}`;
const finalLine = `
<div class="${finalContainerClass}">
<div class="status-final-info">
<div class="status-final-label">Final quiz</div>
<div class="${finalNoteClass}">${escapeHtml(finalNoteText)}</div>
</div>
<div class="status-final-badge">${finalBadge}</div>
</div>
`.trim();
const updatedLabel = escapeHtml(`Updated ${formatRelativeTime(status?.updatedAt)}`);
const errorBlock = errorMessages.length
? `<div class="status-errors"><div>Needs attention:</div><ul>${errorMessages.map(msg => `<li>${escapeHtml(msg)}</li>`).join('')}</ul></div>`
: '';
return `
<div class="status-block">
<div class="status-header">
<div class="status-title">${videoTitle}</div>
</div>
${progressMarkup}
${metricsMarkup}
${finalLine}
<div class="status-updated">${updatedLabel}</div>
${errorBlock}
</div>
`.trim();
}
async function loadGenerationStatus() {
const container = document.getElementById('statusContent');
if (!container) return;
updateStatusSummary('pending', 'Checking…');
container.innerHTML = '<div class="status-placeholder">Checking current video...</div>';
try {
const tab = await getActiveTab();
if (!tab || !isYouTubeWatchUrl(tab.url)) {
updateStatusSummary('skipped', 'Unavailable');
container.innerHTML = '<div class="status-placeholder">Open a YouTube video to see quiz generation progress.</div>';
return;
}
let videoId = null;
try {
const url = new URL(tab.url);
videoId = url.searchParams.get('v');
} catch (err) {
console.warn('LearnTube: Could not parse video ID from URL', err);
}
const statusMap = await chrome.runtime.sendMessage({ type: 'GET_GENERATION_STATUS' }) || {};
const currentStatus = videoId ? statusMap[videoId] : null;
if (!currentStatus) {
updateStatusSummary('pending', 'Waiting');
container.innerHTML = '<div class="status-placeholder">No quiz activity recorded for this video yet.</div>';
return;
}
const overallStatus = deriveOverallStatus(currentStatus);
updateStatusSummary(overallStatus);
container.innerHTML = renderCurrentStatus(currentStatus);
} catch (error) {
console.error('Error loading generation status:', error);
updateStatusSummary('error', 'Error');
container.innerHTML = '<div class="status-placeholder status-error">Unable to load quiz status.</div>';
}
}
async function loadSettings() {
try {
const response = await chrome.runtime.sendMessage({ type: 'GET_SETTINGS' });
if (response) {
settings = { ...settings, ...response };
if (!settings.theme) {
settings.theme = 'light';
}
updateUI();
}
} catch (error) {
console.error('Error loading settings:', error);
}
}
async function saveSettings() {
try {
await chrome.runtime.sendMessage({
type: 'UPDATE_SETTINGS',
settings
});
const tabs = await chrome.tabs.query({ url: '*://*.youtube.com/*' });
tabs.forEach(tab => {
sendMessageToTab(tab.id, { action: 'updateSettings' }).catch(() => { });
});
} catch (error) {
console.error('Error saving settings:', error);
}
}
function updateUI() {
document.getElementById('enabledToggle').checked = settings.enabled;
document.getElementById('autoQuizToggle').checked = settings.autoQuiz;
document.getElementById('finalQuizToggle').checked = settings.finalQuizEnabled;
document.getElementById('questionCount').value = settings.questionCount;
document.getElementById('themeSelect').value = settings.theme || 'light';
// Update theme scope segmented control
const themeScope = settings.themeScope || 'quiz-popup';
const themeScopeButtons = document.querySelectorAll('#themeScope .seg-btn');
themeScopeButtons.forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.scope === themeScope) {
btn.classList.add('active');
}
});
// Update AI provider radio buttons
const provider = settings.aiProvider || 'on-device';
document.getElementById('providerOnDevice').checked = provider === 'on-device';
document.getElementById('providerGemini').checked = provider === 'gemini-api';
// Trigger change event to update summary
document.querySelector('input[name="aiProvider"]:checked').dispatchEvent(new Event('change'));
document.getElementById('geminiApiKey').value = settings.geminiApiKey || '';
applyTheme(settings.theme || 'dark');
updateAIProviderUI();
updateApiKeyStatus();
// Update model provider collapsible state
if (settings.modelProviderExpanded !== undefined) {
const section = document.getElementById('modelProviderSection');
const toggle = document.getElementById('modelProviderToggle');
const content = document.getElementById('modelProviderContent');
if (section && toggle && content) {
if (settings.modelProviderExpanded) {
toggle.setAttribute('aria-expanded', 'true');
content.setAttribute('aria-hidden', 'false');
section.classList.remove('collapsed');
} else {
toggle.setAttribute('aria-expanded', 'false');
content.setAttribute('aria-hidden', 'true');
section.classList.add('collapsed');
}
}
}
const analyticsToggle = document.getElementById('analyticsToggle');
if (analyticsToggle) {
analyticsToggle.checked = settings.analyticsEnabled !== false;
}
}
function updateAIProviderUI() {
const provider = settings.aiProvider || 'on-device';
const apiKeySetting = document.getElementById('geminiApiKeySetting');
const apiKeyActions = document.querySelector('#geminiApiKeySetting + .setting-item');
if (apiKeySetting) {
apiKeySetting.style.display = provider === 'gemini-api' ? 'flex' : 'none';
}
if (apiKeyActions) {
apiKeyActions.style.display = provider === 'gemini-api' ? 'block' : 'none';
}
updateModelStatusDisplay(provider);
}
function updateApiKeyStatus() {
const apiKeyStatus = document.getElementById('apiKeyStatus');
const apiKey = settings.geminiApiKey?.trim();
if (apiKeyStatus) {
if (apiKey && apiKey.length > 0) {
apiKeyStatus.style.display = 'flex';
} else {
apiKeyStatus.style.display = 'none';
}
}
}
function updateModelStatusDisplay(provider) {
const modelStatusContainer = document.querySelector('.model-status');
if (!modelStatusContainer) return;
if (provider === 'gemini-api') {
// Show only Gemini model
modelStatusContainer.innerHTML = `
<div class="model-item">
<div class="model-info">
<div class="model-name">Gemma 3 - 27B</div>
<div class="model-description">Generates quiz questions and summaries</div>
</div>
<div class="model-status-indicator" id="geminiModelStatus">
<div class="status-dot"></div>
<span class="status-text">Checking...</span>
<div class="progress-bar" id="geminiModelProgress" style="display: none;">
<div class="progress-fill"></div>
<span class="progress-text">0%</span>
</div>
</div>
</div>
`;
// Update Gemini status
const apiKey = settings.geminiApiKey?.trim();
if (apiKey) {
updateModelStatus('geminiModelStatus', 'ready', 'API Key Configured', false);
} else {
updateModelStatus('geminiModelStatus', 'not-ready', 'API Key Required', false);
}
} else {
// Show original on-device models
modelStatusContainer.innerHTML = `
<div class="model-item">
<div class="model-info">
<div class="model-name">Language Model</div>
<div class="model-description">Generates quiz questions</div>
</div>
<div class="model-status-indicator" id="languageModelStatus">
<div class="status-dot"></div>
<span class="status-text">Checking...</span>
<div class="progress-bar" id="languageModelProgress" style="display: none;">
<div class="progress-fill"></div>
<span class="progress-text">0%</span>
</div>
</div>
</div>
<div class="model-item">
<div class="model-info">
<div class="model-name">Summarizer</div>
<div class="model-description">Creates video summaries</div>
</div>
<div class="model-status-indicator" id="summarizerStatus">
<div class="status-dot"></div>
<span class="status-text">Checking...</span>
<div class="progress-bar" id="summarizerProgress" style="display: none;">
<div class="progress-fill"></div>
<span class="progress-text">0%</span>
</div>
</div>
</div>
`;
// Restore original model status checking
checkModelStatus();
}
}
function applyTheme(theme) {
const themeScope = settings.themeScope || 'quiz-popup';
// Apply theme to popup based on scope
if (themeScope === 'all-place') {
document.body.setAttribute('data-theme', theme);
} else {
// When scope is quiz-popup, invert the theme for popup
const invertedTheme = theme === 'light' ? 'dark' : 'light';
document.body.setAttribute('data-theme', invertedTheme);
}
// Send theme info to content script for quiz popup theming
updateContentScriptTheme(theme, themeScope);
}
async function updateContentScriptTheme(theme, themeScope) {
try {
const tab = await getActiveYouTubeTab();
if (tab) {
await sendMessageToTab(tab.id, {
type: 'UPDATE_THEME',
theme: theme,
themeScope: themeScope
});
}
} catch (error) {
console.warn('LearnTube: Failed to send theme update to content script:', error);
}
}
async function loadProgress() {
try {
const response = await chrome.runtime.sendMessage({ type: 'GET_PROGRESS' });
if (response) {
calculateStats(response);
}
} catch (error) {
console.error('Error loading progress:', error);
}
}
function calculateStats(progress) {
let totalVideos = 0;
let totalQuizzes = 0;
let totalScore = 0;
let totalQuestions = 0;
for (const videoId in progress) {
totalVideos++;
const video = progress[videoId];
if (video.segments && video.segments.length > 0) {
video.segments.forEach(segment => {
if (segment && segment.total > 0) {
totalQuizzes++;
totalScore += segment.score;
totalQuestions += segment.total;
}
});
}
if (video.final && video.final.total > 0) {
totalQuizzes++;
totalScore += video.final.score;
totalQuestions += video.final.total;
}
}
const avgScore = totalQuestions > 0
? Math.round((totalScore / totalQuestions) * 100)
: 0;
document.getElementById('totalVideos').textContent = totalVideos;
document.getElementById('totalQuizzes').textContent = totalQuizzes;
document.getElementById('avgScore').textContent = `${avgScore}%`;
if (avgScore > 0) {
const scoreElement = document.getElementById('avgScore');
scoreElement.style.color = avgScore >= 70 ? '#10b981' : avgScore >= 50 ? '#f59e0b' : '#ef4444';
}
}
document.getElementById('enabledToggle').addEventListener('change', (e) => {
settings.enabled = e.target.checked;
saveSettings();
});
document.getElementById('autoQuizToggle').addEventListener('change', (e) => {
settings.autoQuiz = e.target.checked;
saveSettings();
});
document.getElementById('finalQuizToggle').addEventListener('change', (e) => {
settings.finalQuizEnabled = e.target.checked;
saveSettings();
});
const analyticsToggleEl = document.getElementById('analyticsToggle');
if (analyticsToggleEl) {
analyticsToggleEl.addEventListener('change', (e) => {
settings.analyticsEnabled = e.target.checked;
saveSettings();
});
}
document.getElementById('questionCount').addEventListener('change', (e) => {
settings.questionCount = parseInt(e.target.value);
saveSettings();
});
document.getElementById('themeSelect').addEventListener('change', (e) => {
settings.theme = e.target.value;
applyTheme(settings.theme);
saveSettings();
});
// Theme scope segmented control event listeners
function setupThemeScopeListeners() {
const themeScopeContainer = document.getElementById('themeScope');
if (!themeScopeContainer) return;
themeScopeContainer.addEventListener('click', (e) => {
if (!e.target.classList.contains('seg-btn')) return;
const newScope = e.target.dataset.scope;
// Update UI
const buttons = themeScopeContainer.querySelectorAll('.seg-btn');
buttons.forEach(b => b.classList.remove('active'));
e.target.classList.add('active');
// Update settings and reapply theme
settings.themeScope = newScope;
applyTheme(settings.theme);
saveSettings();
});
}
// Initialize theme scope listeners
setupThemeScopeListeners();
// Model Provider collapsible functionality
function setupModelProviderCollapsible() {
const toggle = document.getElementById('modelProviderToggle');
const content = document.getElementById('modelProviderContent');
const summary = document.getElementById('modelProviderSummary');
const section = document.getElementById('modelProviderSection');
if (!toggle || !content || !summary || !section) return;
// Apply saved state from settings
function applyModelProviderState() {
const shouldBeExpanded = settings.modelProviderExpanded;
if (shouldBeExpanded) {
toggle.setAttribute('aria-expanded', 'true');
content.setAttribute('aria-hidden', 'false');
section.classList.remove('collapsed');
} else {
toggle.setAttribute('aria-expanded', 'false');
content.setAttribute('aria-hidden', 'true');
section.classList.add('collapsed');
}
}
// Apply initial state
applyModelProviderState();
toggle.addEventListener('click', () => {
const isExpanded = toggle.getAttribute('aria-expanded') === 'true';
toggle.setAttribute('aria-expanded', !isExpanded);
content.setAttribute('aria-hidden', isExpanded);
if (isExpanded) {
section.classList.add('collapsed');
settings.modelProviderExpanded = false;
} else {
section.classList.remove('collapsed');
settings.modelProviderExpanded = true;
}
// Save with other settings
saveSettings();
});
// Update summary when provider changes
function updateProviderSummary() {
const onDeviceRadio = document.getElementById('providerOnDevice');
const geminiRadio = document.getElementById('providerGemini');
if (onDeviceRadio && onDeviceRadio.checked) {
summary.textContent = 'On Device';
summary.className = 'status-pill status-pending';
} else if (geminiRadio && geminiRadio.checked) {
summary.textContent = 'Gemini API';
summary.className = 'status-pill status-ready';
}
}
// Listen for provider changes
document.getElementById('providerOnDevice').addEventListener('change', updateProviderSummary);
document.getElementById('providerGemini').addEventListener('change', updateProviderSummary);
// Initial summary update
updateProviderSummary();
}
// Initialize model provider collapsible
setupModelProviderCollapsible();
// AI Provider radio button handlers
document.getElementById('providerOnDevice').addEventListener('change', (e) => {
if (e.target.checked) {
settings.aiProvider = 'on-device';
updateAIProviderUI();
saveSettings();
}
});
document.getElementById('providerGemini').addEventListener('change', (e) => {
if (e.target.checked) {
settings.aiProvider = 'gemini-api';
updateAIProviderUI();
saveSettings();
}
});
document.getElementById('geminiApiKey').addEventListener('input', (e) => {
settings.geminiApiKey = e.target.value;
updateApiKeyStatus();
updateModelStatusDisplay(settings.aiProvider);
});
document.getElementById('saveApiKey').addEventListener('click', () => {
const apiKey = document.getElementById('geminiApiKey').value.trim();
if (apiKey) {
settings.geminiApiKey = apiKey;
saveSettings();
updateApiKeyStatus();
updateModelStatusDisplay(settings.aiProvider);
// Show success feedback
const saveBtn = document.getElementById('saveApiKey');
const originalText = saveBtn.textContent;
saveBtn.textContent = 'Saved!';
saveBtn.style.background = '#10b981';
setTimeout(() => {
saveBtn.textContent = originalText;
saveBtn.style.background = '#3b82f6';
}, 2000);
}
});
// API Key visibility toggle
document.getElementById('toggleApiKeyVisibility').addEventListener('click', (e) => {
const input = document.getElementById('geminiApiKey');
const button = e.target.closest('button');
const svg = button.querySelector('svg');
if (input.type === 'password') {
input.type = 'text';
svg.innerHTML = '<path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line>';
} else {
input.type = 'password';
svg.innerHTML = '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle>';
}
});
// Get API Key button
document.getElementById('getApiKey').addEventListener('click', () => {
chrome.tabs.create({
url: 'https://aistudio.google.com/api-keys'
});
});
document.getElementById('resetButton').addEventListener('click', async () => {
if (confirm('Are you sure you want to reset everything? This will clear all cache, progress, and settings. This cannot be undone.')) {
try {
// Clear all progress
await chrome.runtime.sendMessage({ type: 'CLEAR_PROGRESS' });
// Clear all cache
await chrome.runtime.sendMessage({ type: 'CLEAR_ALL_CACHE' });
// Reset settings to defaults
settings = {
enabled: true,
autoQuiz: true,
questionCount: 1,
finalQuizEnabled: true,
soundEnabled: true,
theme: 'light',
themeScope: 'quiz-popup',
analyticsEnabled: true,
aiProvider: 'on-device',
geminiApiKey: ''
};
// Save reset settings
await saveSettings();
// Update UI
updateUI();
// Reset progress display
document.getElementById('totalVideos').textContent = '0';
document.getElementById('totalQuizzes').textContent = '0';
document.getElementById('avgScore').textContent = '0%';
const btn = document.getElementById('resetButton');
const originalText = btn.innerHTML;
btn.innerHTML = '✓ Reset Complete';
btn.disabled = true;
setTimeout(() => {
btn.innerHTML = originalText;
btn.disabled = false;
}, 2000);
} catch (error) {
console.error('Error resetting:', error);
}
}
});
document.getElementById('openInstallGuide').addEventListener('click', (event) => {
event.preventDefault();
chrome.tabs.create({
url: 'https://github.com/Sumit189/LearnTube-AI?tab=readme-ov-file#installation'
});
});
document.getElementById('clearCache').addEventListener('click', async () => {
try {
const tab = await getActiveYouTubeTab();
if (!tab) {
alert('Please navigate to a YouTube video first to clear cache!');
return;
}
await sendMessageToTab(tab.id, {
action: 'clearCache'
});
const btn = document.getElementById('clearCache');
btn.innerHTML = '✓ Cache Cleared — Reloading...';
btn.disabled = true;
// Listen for the tab to finish reloading to update button text
const targetTabId = tab.id;
const onUpdated = (updatedTabId, changeInfo) => {
if (updatedTabId === targetTabId && changeInfo.status === 'complete') {
btn.innerHTML = "Clear This Video's Cache";
btn.disabled = false;
chrome.tabs.onUpdated.removeListener(onUpdated);
}
};
chrome.tabs.onUpdated.addListener(onUpdated);
// Reload the current YouTube tab to regenerate quizzes after 1 seconds
setTimeout(() => {
chrome.tabs.reload(targetTabId);
}, 1000);
} catch (error) {
console.error('Error clearing cache:', error);
alert('Error: Could not clear cache. Make sure you are on a YouTube video page.');
}
});
document.getElementById('clearAllCache').addEventListener('click', async () => {
if (!confirm('Are you sure you want to clear ALL cached quizzes and transcripts? This will remove data for all videos.')) {
return;
}
try {
await chrome.runtime.sendMessage({ type: 'CLEAR_ALL_CACHE' });
const btn = document.getElementById('clearAllCache');
const originalText = btn.innerHTML;
btn.innerHTML = '✓ All Cache Cleared';
btn.disabled = true;
setTimeout(() => {