-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmy_progress.js
More file actions
963 lines (843 loc) · 36.8 KB
/
Copy pathmy_progress.js
File metadata and controls
963 lines (843 loc) · 36.8 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
function pct(n) {
if (typeof n !== "number" || Number.isNaN(n)) return "—";
return `${Math.round(n * 100)}%`;
}
function formatAttempts(n) {
if (typeof n !== "number") return "0";
return String(n);
}
function drawLineChart(canvas, labels, accuracyByDay) {
const ctx = canvas.getContext("2d");
const w = canvas.width;
const h = canvas.height;
// Clear
ctx.clearRect(0, 0, w, h);
// Background grid
ctx.strokeStyle = "rgba(255,255,255,0.08)";
ctx.lineWidth = 1;
for (let i = 1; i <= 4; i++) {
const y = (h / 5) * i;
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(w, y);
ctx.stroke();
}
// Build points (skip nulls)
const valid = accuracyByDay
.map((a, idx) => ({ a, idx }))
.filter(p => typeof p.a === "number");
if (valid.length < 2) {
ctx.fillStyle = "rgba(255,255,255,0.7)";
ctx.font = "14px Arial";
ctx.fillText("Complete at least 2 quiz attempts to see a trend.", 16, 28);
return;
}
const xStep = w / (labels.length - 1);
const toY = (acc) => {
// acc: 0..1
const marginTop = 16;
const marginBottom = 24;
const usable = h - marginTop - marginBottom;
return marginTop + (1 - acc) * usable;
};
// Line
ctx.strokeStyle = "#66fcf1";
ctx.lineWidth = 2;
ctx.beginPath();
// Find first valid index
const firstIdx = valid[0].idx;
let started = false;
for (let i = 0; i < accuracyByDay.length; i++) {
const a = accuracyByDay[i];
if (typeof a !== "number") continue;
const x = i * xStep;
const y = toY(a);
if (!started) {
ctx.moveTo(x, y);
started = true;
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
// Points
valid.forEach(({ a, idx }) => {
const x = idx * xStep;
const y = toY(a);
ctx.fillStyle = "#66fcf1";
ctx.beginPath();
ctx.arc(x, y, 4, 0, 2 * Math.PI);
ctx.fill();
});
// X labels (mm/dd)
ctx.fillStyle = "rgba(255,255,255,0.65)";
ctx.font = "12px Arial";
const stride = Math.max(1, Math.floor(labels.length / 6));
labels.forEach((lab, i) => {
if (i % stride !== 0 && i !== labels.length - 1) return;
ctx.fillText(lab, i * xStep - 10, h - 8);
});
}
function init() {
let currentStreak = 0;
let streakMetaText = "No practice yet.";
let dailyGoalPct = 0;
let dailyGoalMetaText = "Complete 1 quiz or review 10 questions.";
if (window.studyProgress && typeof window.studyProgress.loadStreakState === "function") {
const streakState = window.studyProgress.loadStreakState();
currentStreak = streakState.currentStreak || 0;
const last = streakState.lastActiveDate;
streakMetaText = last ? `Last active: ${last}` : "No activity yet.";
const qDone = streakState.dailyGoalProgress.quizzesCompleted || 0;
const rDone = streakState.dailyGoalProgress.questionsReviewed || 0;
const quizGoalProgress = qDone / 1;
const reviewGoalProgress = rDone / 10;
dailyGoalPct = Math.min(100, Math.round(Math.max(quizGoalProgress, reviewGoalProgress) * 100));
dailyGoalMetaText = dailyGoalPct >= 100
? `🎉 Goal Achieved! (${qDone}/1 quiz, ${rDone}/10 reviewed)`
: `${qDone}/1 quiz, ${rDone}/10 reviewed today`;
} else {
const streak = window.quizProgress.getStreak();
currentStreak = streak.currentStreak || 0;
const last = streak.lastPracticeDate;
streakMetaText = last ? `Last practice: ${last}` : "No practice yet.";
}
const streakValue = document.getElementById("streakValue");
const streakMeta = document.getElementById("streakMeta");
if (streakValue) streakValue.textContent = String(currentStreak);
if (streakMeta) streakMeta.textContent = streakMetaText;
const dailyGoalValue = document.getElementById("dailyGoalValue");
const dailyGoalMeta = document.getElementById("dailyGoalMeta");
if (dailyGoalValue) dailyGoalValue.textContent = `${dailyGoalPct}%`;
if (dailyGoalMeta) dailyGoalMeta.textContent = dailyGoalMetaText;
const overall = window.quizProgress.getOverallAccuracy();
const overallAccuracyValue = document.getElementById("overallAccuracyValue");
const overallAccuracyMeta = document.getElementById("overallAccuracyMeta");
if (overallAccuracyValue) overallAccuracyValue.textContent = overall.accuracy == null ? "—" : pct(overall.accuracy);
if (overallAccuracyMeta) {
overallAccuracyMeta.textContent = overall.total > 0 ? `${overall.correct} correct out of ${overall.total} answers` : "Complete a quiz to populate your stats.";
}
// Chart
const series = window.quizProgress.getAccuracySeries({ days: 14 });
const canvas = document.getElementById("accuracyChart");
if (canvas) {
// Ensure canvas resolution matches layout size
// (Canvas width/height are attributes; default may be too small.)
const rect = canvas.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
canvas.width = Math.floor(rect.width * dpr);
canvas.height = Math.floor(240 * dpr);
drawLineChart(canvas, series.labels, series.accuracyByDay);
}
// Topic stats
const topicStatsEl = document.getElementById("topicStats");
const byTopic = window.quizProgress.getAllTopicStats();
if (topicStatsEl) {
const topics = window.quizProgress.QUIZ_TOPICS;
const sorted = [...topics].sort((a, b) => {
const aAttempts = byTopic[a.id]?.attempts || 0;
const bAttempts = byTopic[b.id]?.attempts || 0;
return (bAttempts - aAttempts) || String(a.label).localeCompare(String(b.label));
});
topicStatsEl.innerHTML = `
<div style="display: flex; justify-content: space-between; font-size: 11px; font-weight: bold; text-transform: uppercase; letter-spacing: 0.5px; color: rgba(255,255,255,0.5); border-bottom: 1px solid rgba(255,255,255,0.06); padding-bottom: 6px; margin-bottom: 8px;">
<span style="min-width: 210px;">Topic</span>
<span style="flex: 1; margin: 0 10px; text-align: center;">Accuracy Trend</span>
<span style="min-width: 92px; text-align: right;">Stats</span>
</div>
`;
sorted.forEach(t => {
const agg = byTopic[t.id];
const attempts = agg?.attempts || 0;
const qTotal = agg?.questionsTotal || 0;
const correctTotal = agg?.correctTotal || 0;
const accuracy = qTotal > 0 ? correctTotal / qTotal : null;
const barW = accuracy == null ? 0 : Math.max(0, Math.min(100, Math.round(accuracy * 100)));
const row = document.createElement("div");
row.className = "topic-row";
row.innerHTML = `
<div style="min-width: 210px; font-weight: 600">${t.label}</div>
<div class="bar" aria-label="accuracy bar">
<i style="width:${barW}%; background:${accuracy == null ? "rgba(255,255,255,0.22)" : "#66fcf1"}"></i>
</div>
<div style="min-width: 92px; text-align:right">
<div style="font-weight:700">${accuracy == null ? "—" : pct(accuracy)}</div>
<div class="muted" style="font-size:12px">${formatAttempts(attempts)} attempts</div>
</div>
`;
topicStatsEl.appendChild(row);
});
}
// Recommendations
const recEl = document.getElementById("recommendedTopics");
if (recEl) {
const recs = window.quizProgress.getRecommendedTopics({ limit: 3 });
recEl.innerHTML = "";
recs.forEach(r => {
const chip = document.createElement("span");
chip.className = "recommend-chip";
const accText = r.accuracy == null ? "not attempted" : `accuracy ${pct(r.accuracy)}`;
chip.textContent = `${r.topic.label} • ${accText}`;
recEl.appendChild(chip);
});
}
}
function initReviewQueueWidget() {
const widget = document.getElementById("reviewQueueWidget");
if (!widget) return;
const STORAGE_KEY = "learnsphere_review_schedule_v1";
let schedule = {};
try {
schedule = JSON.parse(localStorage.getItem(STORAGE_KEY)) || {};
} catch {
schedule = {};
}
// Topic IDs must match progress.js topic list.
const TOPIC_IDS = [
"physics-motion",
"physics-nlm",
"physics-projectile",
"physics-ray",
"maths-calculus",
"maths-vectors",
"maths-probability",
"maths-geometry",
"chemistry-atomic",
"chemistry-bonding",
"chemistry-equil",
"chemistry-thermo",
];
// Use the same day-token rules as spaced repetition logic in progress.js/review.js.
function todayLocalISODate() {
const d = new Date();
const yyyy = d.getFullYear();
const mm = String(d.getMonth() + 1).padStart(2, "0");
const dd = String(d.getDate()).padStart(2, "0");
return `${yyyy}-${mm}-${dd}`;
}
function parseISODateToUTCStart(isoDateYYYYMMDD) {
const [y, m, day] = isoDateYYYYMMDD.split("-").map(Number);
const dt = new Date(y, m - 1, day, 0, 0, 0, 0);
return Math.floor(dt.getTime() / 86400000);
}
const todayToken = parseISODateToUTCStart(todayLocalISODate());
let dueCount = 0;
const nextDates = [];
for (const topicId of TOPIC_IDS) {
const s = schedule[topicId];
if (!s || !s.nextReviewDate) continue;
const nextToken = parseISODateToUTCStart(s.nextReviewDate);
if (todayToken >= nextToken) dueCount += 1;
else nextDates.push(s.nextReviewDate);
}
if (dueCount > 0) {
widget.innerHTML = `<a href="review.html" style="color: var(--accent-color); text-decoration: none; font-weight: bold;">${dueCount} review${dueCount === 1 ? "" : "s"} due today. Click here to start review.</a>`;
} else {
const earliest = nextDates.sort().shift();
widget.innerHTML = earliest ? `Next review available on ${earliest}. <a href="review.html" style="color: var(--accent-color); text-decoration: none; font-weight: bold;">View queue</a>` : `No reviews scheduled yet. Complete topics to start getting review sessions. <a href="review.html" style="color: var(--accent-color); text-decoration: none; font-weight: bold;">View queue</a>`;
}
}
function initMasteryDashboard() {
const masteryListEl = document.getElementById("masterySkillsList");
const weakSkillsEl = document.getElementById("weakSkillsRecommendations");
if (!masteryListEl || !weakSkillsEl) return;
const mastery = window.quizProgress.getMasteryStats();
const taxonomy = window.quizProgress.SKILL_TAXONOMY || {};
// Group all unique skills from taxonomy
const skillMap = new Map();
for (const [qText, tax] of Object.entries(taxonomy)) {
if (!skillMap.has(tax.skillId)) {
skillMap.set(tax.skillId, {
skillId: tax.skillId,
label: tax.label,
topicId: tax.topicId,
quizUrl: tax.quizUrl,
attempts: 0,
correct: 0
});
}
}
// Populate actual attempts and correct values
let totalAttempts = 0;
for (const [sId, m] of Object.entries(mastery)) {
totalAttempts += m.attempts || 0;
if (skillMap.has(sId)) {
const entry = skillMap.get(sId);
entry.attempts = m.attempts || 0;
entry.correct = m.correct || 0;
} else {
// Fallback for dynamically generated or legacy general skills
skillMap.set(sId, {
skillId: sId,
label: sId.replace("-general", " General Concepts"),
topicId: sId.split("-")[0],
quizUrl: null,
attempts: m.attempts || 0,
correct: m.correct || 0
});
}
}
const skillsArray = Array.from(skillMap.values());
// Render Left Column: Concept Mastery Details
// Sort attempted first, then alphabetical by label
skillsArray.sort((a, b) => {
if (a.attempts !== b.attempts) {
return b.attempts - a.attempts; // attempted first
}
return a.label.localeCompare(b.label);
});
if (totalAttempts === 0) {
masteryListEl.innerHTML = `<div class="muted" style="padding: 12px; text-align: center;">No mastery data recorded yet. Complete quizzes to see concept-wise stats!</div>`;
} else {
masteryListEl.innerHTML = `
<div style="display: flex; justify-content: space-between; font-size: 11px; font-weight: bold; text-transform: uppercase; letter-spacing: 0.5px; color: rgba(255,255,255,0.5); border-bottom: 1px solid rgba(255,255,255,0.06); padding-bottom: 6px; margin-bottom: 8px;">
<span style="min-width: 210px;">Concept</span>
<span style="flex: 1; margin: 0 12px; text-align: center;">Mastery level</span>
<span style="min-width: 90px; text-align: right;">Accuracy</span>
</div>
`;
skillsArray.forEach(s => {
// Only render if attempted to keep the dashboard clean and focused on progress
if (s.attempts === 0) return;
const accuracy = s.attempts > 0 ? s.correct / s.attempts : 0;
const pctValue = Math.round(accuracy * 100);
// Determine premium color based on accuracy
let barColor = "#ef4444"; // red for <50%
if (pctValue >= 80) {
barColor = "#66fcf1"; // teal for >=80%
} else if (pctValue >= 50) {
barColor = "#f59e0b"; // orange/yellow for 50-80%
}
const row = document.createElement("div");
row.className = "topic-row";
row.style.marginBottom = "8px";
row.innerHTML = `
<div style="min-width: 210px; font-weight: 600; font-size: 0.9rem;">${s.label}</div>
<div class="bar" aria-label="mastery bar" style="background: rgba(255, 255, 255, 0.05); margin: 0 12px; height: 8px;">
<i style="width:${pctValue}%; background:${barColor}; border-radius: 999px;"></i>
</div>
<div style="min-width: 90px; text-align:right; font-size: 0.9rem;">
<div style="font-weight:700; color: ${barColor};">${pctValue}%</div>
<div class="muted" style="font-size:11px;">${s.correct}/${s.attempts} correct</div>
</div>
`;
masteryListEl.appendChild(row);
});
if (masteryListEl.children.length === 0) {
masteryListEl.innerHTML = `<div class="muted" style="padding: 12px; text-align: center;">Complete quizzes to see concept-wise stats!</div>`;
}
}
// Render Right Column: Weakest Concepts & Recommended Practice
const weakSkills = window.quizProgress.getWeakestSkills({ limit: 3 });
weakSkillsEl.innerHTML = "";
if (!weakSkills || weakSkills.length === 0) {
weakSkillsEl.innerHTML = `<div class="muted">No weak concepts identified yet. Keep practicing!</div>`;
} else {
weakSkills.forEach(ws => {
const accuracyPct = ws.attempts > 0 ? `${Math.round(ws.accuracy * 100)}%` : "Not attempted";
const card = document.createElement("div");
card.style.background = "rgba(255, 255, 255, 0.02)";
card.style.border = "1px solid rgba(255, 255, 255, 0.06)";
card.style.borderRadius = "8px";
card.style.padding = "12px 14px";
card.style.display = "flex";
card.style.justifyContent = "space-between";
card.style.alignItems = "center";
card.style.transition = "all 0.2s ease";
card.addEventListener("mouseenter", () => {
card.style.background = "rgba(255, 255, 255, 0.04)";
card.style.borderColor = "rgba(102, 252, 241, 0.3)";
});
card.addEventListener("mouseleave", () => {
card.style.background = "rgba(255, 255, 255, 0.02)";
card.style.borderColor = "rgba(255, 255, 255, 0.06)";
});
const practiceUrl = ws.quizUrl ? ws.quizUrl : "#";
let statusColor = "#ff5e5e";
if (ws.attempts === 0) {
statusColor = "#a0aec0";
} else if (ws.accuracy >= 0.8) {
statusColor = "#66fcf1";
} else if (ws.accuracy >= 0.5) {
statusColor = "#f59e0b";
}
card.innerHTML = `
<div style="display:flex; flex-direction:column; gap:4px; text-align:left;">
<div style="font-weight: 600; font-size: 0.95rem; color: #fff;">${ws.label}</div>
<div style="font-size: 0.8rem; color: rgba(255, 255, 255, 0.65);">
Accuracy: <span style="font-weight:bold; color: ${statusColor}">${accuracyPct}</span>
${ws.attempts > 0 ? `(${ws.attempts} attempts)` : ""}
</div>
</div>
${ws.quizUrl ? `
<a href="${practiceUrl}" style="
background: rgba(102, 252, 241, 0.08);
border: 1px solid rgba(102, 252, 241, 0.4);
color: #66fcf1;
padding: 6px 12px;
border-radius: 6px;
text-decoration: none;
font-size: 0.8rem;
font-weight: bold;
transition: all 0.2s ease;
" onmouseover="this.style.background='#66fcf1'; this.style.color='#0f1115'" onmouseout="this.style.background='rgba(102, 252, 241, 0.08)'; this.style.color='#66fcf1'">
Practice ➔
</a>
` : ""}
`;
weakSkillsEl.appendChild(card);
});
}
}
document.addEventListener("DOMContentLoaded", () => {
init();
initMasteryDashboard();
initReviewQueueWidget();
// Export Progress UI wiring
const downloadBtn = document.getElementById("downloadProgressJsonBtn");
const printBtn = document.getElementById("printProgressBtn");
const previewBtn = document.getElementById("previewExportBtn");
const previewContainer = document.getElementById("exportPreviewContainer");
const previewContent = document.getElementById("exportPreviewContent");
const previewWarning = document.getElementById("exportPreviewWarning");
const closePreviewBtn = document.getElementById("closePreviewBtn");
if (downloadBtn) {
downloadBtn.addEventListener("click", () => {
if (!window.exportProgress?.buildProgressExportPayload || !window.exportProgress?.downloadJson) return;
const payload = window.exportProgress.buildProgressExportPayload({
formatVersion: { major: 1, minor: 0 },
roleContext: "learner"
});
window.exportProgress.downloadJson(payload, "learnsphere_progress_export.json");
});
}
if (printBtn) {
printBtn.addEventListener("click", () => {
window.print();
});
}
if (previewBtn && previewContainer && previewContent && previewWarning) {
previewBtn.addEventListener("click", () => {
if (!window.exportProgress?.buildProgressExportPayload) return;
const payload = window.exportProgress.buildProgressExportPayload({
formatVersion: { major: 1, minor: 0 },
roleContext: "learner"
});
// Validate empty states
const attemptsCount = payload?.metrics?.quizHistory?.totalAttempts || 0;
if (attemptsCount === 0) {
previewWarning.style.display = "block";
previewWarning.textContent = "⚠️ [Empty State Check] No quiz attempts recorded yet. The generated export payload will contain empty progress metrics.";
} else {
previewWarning.style.display = "none";
}
previewContent.textContent = JSON.stringify(payload, null, 2);
previewContainer.style.display = "block";
previewContainer.scrollIntoView({ behavior: "smooth" });
});
}
if (closePreviewBtn && previewContainer) {
closePreviewBtn.addEventListener("click", () => {
previewContainer.style.display = "none";
});
}
// ── CSV Download ──
const csvBtn = document.getElementById("downloadProgressCsvBtn");
if (csvBtn) {
csvBtn.addEventListener("click", () => {
if (!window.exportProgress?.buildProgressExportPayload || !window.exportProgress?.downloadCsv) return;
const payload = window.exportProgress.buildProgressExportPayload({
formatVersion: { major: 1, minor: 0 },
roleContext: "learner"
});
window.exportProgress.downloadCsv(payload, "learnsphere_progress_export.csv");
});
}
// ── Create Shareable Link ──
const shareLinkBtn = document.getElementById("createShareableLinkBtn");
if (shareLinkBtn) {
shareLinkBtn.addEventListener("click", async () => {
if (!window.exportProgress?.createShareableSnapshot) return;
shareLinkBtn.disabled = true;
shareLinkBtn.textContent = "⏳ Creating…";
try {
const { shareUrl } = await window.exportProgress.createShareableSnapshot();
showShareModal(shareUrl);
renderSnapshotHistory();
} catch (err) {
console.error("Snapshot creation failed:", err);
alert("Failed to create snapshot. See console for details.");
} finally {
shareLinkBtn.disabled = false;
shareLinkBtn.textContent = "🔗 Create Shareable Link";
}
});
}
// ── Snapshot History ──
const snapshotHistorySection = document.getElementById("snapshotHistorySection");
const snapshotHistoryList = document.getElementById("snapshotHistoryList");
const closeHistoryBtn = document.getElementById("closeSnapshotHistory");
const genSnapshotBtn = document.getElementById("generateSnapshotBtn");
if (genSnapshotBtn) {
// Enhance existing Generate Snapshot button to also show history
const originalHandler = genSnapshotBtn.onclick;
genSnapshotBtn.addEventListener("click", async () => {
if (!window.exportProgress?.generateSnapshot) return;
genSnapshotBtn.disabled = true;
genSnapshotBtn.textContent = "⏳ Generating…";
try {
await window.exportProgress.generateSnapshot();
renderSnapshotHistory();
} catch (err) {
console.error("Snapshot generation failed:", err);
} finally {
genSnapshotBtn.disabled = false;
genSnapshotBtn.textContent = "Generate Snapshot";
}
});
}
if (closeHistoryBtn && snapshotHistorySection) {
closeHistoryBtn.addEventListener("click", () => {
snapshotHistorySection.style.display = "none";
});
}
function renderSnapshotHistory() {
if (!snapshotHistorySection || !snapshotHistoryList) return;
const snapshots = window.exportProgress?.listSnapshots?.() || [];
if (snapshots.length === 0) {
snapshotHistorySection.style.display = "none";
return;
}
snapshotHistorySection.style.display = "block";
snapshotHistoryList.innerHTML = "";
// Show newest first
const sorted = [...snapshots].reverse();
sorted.forEach(snap => {
const item = document.createElement("div");
item.className = "snapshot-history-item";
const dateStr = snap.generatedAt
? new Date(snap.generatedAt).toLocaleString()
: snap.exportId;
const base = window.location.href.split("?")[0].split("#")[0];
const snapUrl = `${base}?snapshot=${encodeURIComponent(snap.exportId)}`;
item.innerHTML = `
<div style="flex: 1;">
<div style="font-weight: 600; color: rgba(255,255,255,0.9);">${dateStr}</div>
<div style="font-size: 11px; color: rgba(255,255,255,0.45); margin-top: 2px; font-family: monospace; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 220px;">${snap.exportId}</div>
</div>
<div class="snap-actions">
<button class="snap-copy" data-url="${snapUrl}" title="Copy link">📋 Copy</button>
<button class="snap-view" data-id="${snap.exportId}" title="View snapshot">👁 View</button>
<button class="snap-delete" data-id="${snap.exportId}" title="Delete snapshot">✕</button>
</div>
`;
snapshotHistoryList.appendChild(item);
});
// Delegate click events
snapshotHistoryList.addEventListener("click", (e) => {
const btn = e.target.closest("button");
if (!btn) return;
if (btn.classList.contains("snap-copy")) {
const url = btn.dataset.url;
navigator.clipboard.writeText(url).then(() => {
btn.textContent = "✓ Copied!";
setTimeout(() => { btn.textContent = "📋 Copy"; }, 1500);
}).catch(() => {
showShareModal(url);
});
}
if (btn.classList.contains("snap-view")) {
const id = btn.dataset.id;
const base = window.location.href.split("?")[0].split("#")[0];
window.location.href = `${base}?snapshot=${encodeURIComponent(id)}`;
}
if (btn.classList.contains("snap-delete")) {
const id = btn.dataset.id;
if (confirm("Delete this snapshot?")) {
window.exportProgress?.deleteSnapshot?.(id);
renderSnapshotHistory();
}
}
});
}
// Show history if any snapshots exist
renderSnapshotHistory();
// ── Share Modal ──
function showShareModal(shareUrl) {
// Remove existing modal if any
const existing = document.querySelector(".share-modal-overlay");
if (existing) existing.remove();
const overlay = document.createElement("div");
overlay.className = "share-modal-overlay";
overlay.innerHTML = `
<div class="share-modal">
<h3>🔗 Shareable Progress Link</h3>
<div class="sub">Share this link to let others view your progress snapshot (read-only). Currently stored locally in this browser.</div>
<div class="url-box">
<input type="text" id="shareUrlInput" value="${shareUrl}" readonly />
<button class="copy-btn" id="copyShareUrlBtn">Copy</button>
</div>
<div class="modal-footer">
<button class="close-modal-btn" id="closeShareModal">Close</button>
</div>
</div>
`;
document.body.appendChild(overlay);
const input = document.getElementById("shareUrlInput");
const copyBtn = document.getElementById("copyShareUrlBtn");
const closeBtn = document.getElementById("closeShareModal");
if (input) {
input.addEventListener("focus", () => input.select());
}
if (copyBtn && input) {
copyBtn.addEventListener("click", () => {
navigator.clipboard.writeText(input.value).then(() => {
copyBtn.textContent = "✓ Copied!";
setTimeout(() => { copyBtn.textContent = "Copy"; }, 2000);
}).catch(() => {
input.select();
document.execCommand("copy");
copyBtn.textContent = "✓ Copied!";
setTimeout(() => { copyBtn.textContent = "Copy"; }, 2000);
});
});
}
if (closeBtn) {
closeBtn.addEventListener("click", () => overlay.remove());
}
// Close on backdrop click
overlay.addEventListener("click", (e) => {
if (e.target === overlay) overlay.remove();
});
}
// ── Snapshot URL Auto-Load ──
(function checkSnapshotUrl() {
const snapshotId = window.exportProgress?.getSnapshotIdFromUrl?.();
if (!snapshotId) return;
const snapshot = window.exportProgress.loadSnapshot(snapshotId);
const banner = document.getElementById("snapshotBanner");
const bannerInfo = document.getElementById("snapshotBannerInfo");
const closeBannerBtn = document.getElementById("closeSnapshotBanner");
if (!snapshot) {
// Snapshot not found in this browser's localStorage
if (banner && bannerInfo) {
bannerInfo.textContent = `Snapshot "${snapshotId}" not found in this browser. It may have been created on a different device.`;
bannerInfo.style.color = "#f59e0b";
banner.style.display = "flex";
banner.style.borderColor = "rgba(245, 158, 11, 0.35)";
banner.style.background = "linear-gradient(135deg, rgba(245, 158, 11, 0.12), rgba(217, 119, 6, 0.08))";
}
} else {
// Show read-only banner with snapshot info
if (banner && bannerInfo) {
const ts = snapshot.generatedAt
? new Date(snapshot.generatedAt).toLocaleString()
: "Unknown date";
bannerInfo.innerHTML = `You are viewing a <strong>read-only progress snapshot</strong> from ${ts}.`;
banner.style.display = "flex";
}
// Populate the preview with snapshot data
if (previewContainer && previewContent) {
previewContent.textContent = JSON.stringify(snapshot.payload, null, 2);
previewContainer.style.display = "block";
// Update the preview header to indicate it's a snapshot
const previewHeader = previewContainer.querySelector("h3 span");
if (previewHeader) previewHeader.textContent = "📸 Snapshot Data (Read-Only)";
}
}
if (closeBannerBtn && banner) {
closeBannerBtn.addEventListener("click", () => {
banner.style.display = "none";
});
}
})();
// Populate print-only report container before printing.
window.addEventListener("beforeprint", () => {
try {
const container = document.getElementById("printReport");
if (!container) return;
const generatedAt = container.querySelector(".muted")?.textContent || "";
const payload = window.exportProgress?.buildProgressExportPayload?.({
formatVersion: { major: 1, minor: 0 },
roleContext: "learner"
});
// Set generatedAt (first occurrence of {{generatedAt}} in the inline template)
const headerMuteds = container.querySelectorAll(".muted");
// Best-effort: update any text that looks like the placeholder.
headerMuteds.forEach(el => {
if (el.textContent && el.textContent.includes("{{generatedAt}}")) {
el.textContent = payload?.generatedAt || new Date().toISOString();
}
});
const streakValue = document.getElementById("streakValue");
const streakMeta = document.getElementById("streakMeta");
const overallAccValue = document.getElementById("overallAccuracyValue");
const overallAccMeta = document.getElementById("overallAccuracyMeta");
const pStreakValue = document.getElementById("printStreakValue");
const pStreakMeta = document.getElementById("printStreakMeta");
const pOverallAccValue = document.getElementById("printOverallAccuracyValue");
const pOverallAccMeta = document.getElementById("printOverallAccuracyMeta");
if (pStreakValue && streakValue) pStreakValue.textContent = streakValue.textContent || "—";
if (pStreakMeta && streakMeta) pStreakMeta.textContent = streakMeta.textContent || "—";
if (pOverallAccValue && overallAccValue) pOverallAccValue.textContent = overallAccValue.textContent || "—";
if (pOverallAccMeta && overallAccMeta) pOverallAccMeta.textContent = overallAccMeta.textContent || "—";
// Weak skills
const printWeakSkills = document.getElementById("printWeakSkills");
if (printWeakSkills && window.quizProgress?.getWeakestSkills) {
const weak = window.quizProgress.getWeakestSkills({ limit: 3 }) || [];
printWeakSkills.innerHTML = `
<div style="display: flex; justify-content: space-between; font-size: 11px; font-weight: bold; text-transform: uppercase; letter-spacing: 0.5px; color: rgba(255,255,255,0.5); border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 6px; margin-bottom: 8px;">
<span>Concept/Skill</span>
<span style="text-align: right;">Performance</span>
</div>
`;
weak.forEach(ws => {
const accTxt = ws.attempts > 0 && ws.accuracy != null ? `${Math.round(ws.accuracy * 100)}%` : "Not attempted";
const el = document.createElement("div");
el.style.border = "1px solid rgba(255,255,255,0.12)";
el.style.borderRadius = "10px";
el.style.padding = "10px 12px";
el.style.background = "rgba(255,255,255,0.02)";
el.innerHTML = `
<div style="font-weight:800;">${ws.label}</div>
<div class="muted" style="font-size:12px; margin-top:4px;">Accuracy: <b style="color:#66fcf1;">${accTxt}</b> ${ws.attempts ? `(${ws.attempts} attempts)` : ""}</div>
`;
printWeakSkills.appendChild(el);
});
}
// Topic stats (top 8 by attempts)
const printTopicStats = document.getElementById("printTopicStats");
if (printTopicStats && window.quizProgress?.getAllTopicStats && window.quizProgress?.QUIZ_TOPICS) {
const byTopic = window.quizProgress.getAllTopicStats() || {};
const topics = window.quizProgress.QUIZ_TOPICS || [];
const rows = topics
.map(t => {
const agg = byTopic[t.id] || {};
const attempts = agg.attempts || 0;
const qTotal = agg.questionsTotal || 0;
const correctTotal = agg.correctTotal || 0;
const accuracy = qTotal > 0 ? (correctTotal / qTotal) : null;
return { topicId: t.id, label: t.label, attempts, questionsTotal: qTotal, accuracy };
})
.sort((a, b) => (b.attempts - a.attempts) || String(a.label).localeCompare(String(b.label)))
.slice(0, 8);
printTopicStats.innerHTML = `
<div style="display: flex; justify-content: space-between; font-size: 11px; font-weight: bold; text-transform: uppercase; letter-spacing: 0.5px; color: rgba(255,255,255,0.5); border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 6px; margin-bottom: 8px;">
<span>Topic</span>
<span style="text-align: right;">Accuracy & Attempts</span>
</div>
`;
rows.forEach(r => {
const accTxt = r.accuracy == null ? "—" : `${Math.round(r.accuracy * 100)}%`;
const barW = r.accuracy == null ? 0 : Math.max(0, Math.min(100, Math.round(r.accuracy * 100)));
const el = document.createElement("div");
el.style.border = "1px solid rgba(255,255,255,0.12)";
el.style.borderRadius = "10px";
el.style.padding = "10px 12px";
el.style.background = "rgba(255,255,255,0.02)";
el.innerHTML = `
<div style="display:flex; justify-content:space-between; gap:12px; align-items:center;">
<div style="font-weight:800;">${r.label}</div>
<div class="muted" style="font-size:12px;">${accTxt} • ${r.attempts} attempts</div>
</div>
<div style="margin-top:8px; height:8px; border-radius:999px; background: rgba(255,255,255,0.07); overflow:hidden;">
<div style="height:100%; width:${barW}%; background:#66fcf1;"></div>
</div>
`;
printTopicStats.appendChild(el);
});
}
// Accuracy chart for print: re-draw using canvas inside printReport.
const printCanvas = document.getElementById("printAccuracyChart");
if (printCanvas && window.quizProgress?.getAccuracySeries) {
const series = window.quizProgress.getAccuracySeries({ days: 14 }) || null;
if (series?.labels && Array.isArray(series.accuracyByDay)) {
const ctx = printCanvas.getContext("2d");
// Basic redraw (simplified) to avoid importing canvas helpers.
ctx.clearRect(0, 0, printCanvas.width, printCanvas.height);
// Grid
ctx.strokeStyle = "rgba(255,255,255,0.08)";
ctx.lineWidth = 1;
for (let i = 1; i <= 4; i++) {
const y = (printCanvas.height / 5) * i;
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(printCanvas.width, y);
ctx.stroke();
}
const marginTop = 16;
const marginBottom = 24;
const usable = printCanvas.height - marginTop - marginBottom;
const toY = (acc) => marginTop + (1 - acc) * usable;
const labels = series.labels;
const xStep = printCanvas.width / (labels.length - 1);
// Line
ctx.strokeStyle = "#66fcf1";
ctx.lineWidth = 2;
ctx.beginPath();
let started = false;
for (let i = 0; i < series.accuracyByDay.length; i++) {
const a = series.accuracyByDay[i];
if (typeof a !== "number") continue;
const x = i * xStep;
const y = toY(a);
if (!started) {
ctx.moveTo(x, y);
started = true;
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
// Points
ctx.fillStyle = "#66fcf1";
for (let i = 0; i < series.accuracyByDay.length; i++) {
const a = series.accuracyByDay[i];
if (typeof a !== "number") continue;
const x = i * xStep;
const y = toY(a);
ctx.beginPath();
ctx.arc(x, y, 4, 0, 2 * Math.PI);
ctx.fill();
}
// X labels
ctx.fillStyle = "rgba(255,255,255,0.65)";
ctx.font = "12px Arial";
const stride = Math.max(1, Math.floor(labels.length / 6));
for (let i = 0; i < labels.length; i++) {
if (i % stride !== 0 && i !== labels.length - 1) continue;
ctx.fillText(labels[i], i * xStep - 10, printCanvas.height - 8);
}
}
}
// Ensure print-only container becomes visible for the printer.
container.style.display = "block";
} catch {}
});
window.addEventListener("afterprint", () => {
const container = document.getElementById("printReport");
if (container) container.style.display = "none";
});
if (window.achievements?.renderBadges) {
window.achievements.renderBadges("badgesContainerMyProgress");
}
if (window.achievements?.renderStreakTimeline) {
window.achievements.renderStreakTimeline("streakTimelineContainer");
}
// Notification Center inline card
if (window.notifications?.renderNotificationCenter) {
window.notifications.renderNotificationCenter("notifCenterContainer");
}
// Update the inline unread badge in the NC card header
(function updateNCBadge() {
const badge = document.getElementById("nc-unread-badge");
if (!badge) return;
const unread = window.notifications?.getUnread?.() || [];
if (unread.length > 0) {
badge.textContent = `${unread.length} unread`;
badge.style.display = "inline";
} else {
badge.style.display = "none";
}
})();
});