-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathreview.js
More file actions
1060 lines (931 loc) · 36.6 KB
/
Copy pathreview.js
File metadata and controls
1060 lines (931 loc) · 36.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
/*
* review.js — Spaced Repetition Review Mode & Dashboard Controller
*
* Provides review quiz runner and updates per-topic nextReviewDate using spaced repetition logic
* stored in progress.js localStorage key:
* learnsphere_review_schedule_v1
*
* Exposes methods to load lists, display stats, and timeline history.
*/
(function () {
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, d] = isoDateYYYYMMDD.split("-").map(Number);
const dt = new Date(y, m - 1, d, 0, 0, 0, 0);
return Math.floor(dt.getTime() / 86400000);
}
function _addDaysISO(isoDateYYYYMMDD, days) {
const token = _parseISODateToUTCStart(isoDateYYYYMMDD);
const target = token + days;
const dt = new Date(target * 86400000);
const yyyy = dt.getFullYear();
const mm = String(dt.getMonth() + 1).padStart(2, "0");
const dd = String(dt.getDate()).padStart(2, "0");
return `${yyyy}-${mm}-${dd}`;
}
const REVIEW_SCHEDULE_KEY = "learnsphere_review_schedule_v1";
const REVIEW_HISTORY_KEY = "learnsphere_review_history_v1";
// NOTE:
// review.js must stay in sync with the app's authoritative topic registry
// (TOPICS in progress.js). If progress.js hasn't loaded yet, we must NOT
// fall back to an alternate metadata set because it can diverge.
function getTopicsList() {
if (typeof TOPICS === "undefined") return null;
if (!Array.isArray(TOPICS)) return null;
// Basic shape check
const ok = TOPICS.every(t => t && typeof t.id === "string" && typeof t.label === "string" && typeof t.subject === "string");
return ok ? TOPICS : null;
}
async function waitForTopicsList({ timeoutMs = 3000, pollIntervalMs = 50 } = {}) {
const start = Date.now();
return new Promise(resolve => {
function tick() {
const topics = getTopicsList();
if (topics) return resolve(topics);
if (Date.now() - start >= timeoutMs) return resolve(null);
setTimeout(tick, pollIntervalMs);
}
tick();
});
}
function loadSchedule() {
try {
return JSON.parse(localStorage.getItem(REVIEW_SCHEDULE_KEY)) || {};
} catch {
return {};
}
}
function saveSchedule(map) {
try {
localStorage.setItem(REVIEW_SCHEDULE_KEY, JSON.stringify(map));
} catch (e) {
console.warn("LearnSphere: Could not save review schedule.", e);
}
}
function loadHistory() {
try {
return JSON.parse(localStorage.getItem(REVIEW_HISTORY_KEY)) || [];
} catch {
return [];
}
}
function saveHistory(list) {
try {
localStorage.setItem(REVIEW_HISTORY_KEY, JSON.stringify(list));
} catch (e) {
console.warn("LearnSphere: Could not save review history.", e);
}
}
function _updateUnifiedStreakAndGoal(type, value = 1) {
if (window.studyProgress && typeof window.studyProgress.recordActivity === "function") {
window.studyProgress.recordActivity(type, value);
return;
}
const STREAK_KEY = "learnsphere_streak_state_v1";
const today = (function() {
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, d] = isoDateYYYYMMDD.split("-").map(Number);
const dt = new Date(y, m - 1, d, 0, 0, 0, 0);
return Math.floor(dt.getTime() / 86400000);
}
let state = { lastActiveDate: null, currentStreak: 0, dailyGoalProgress: { quizzesCompleted: 0, questionsReviewed: 0 } };
try {
const raw = localStorage.getItem(STREAK_KEY);
if (raw) {
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === "object") {
state = parsed;
}
}
} catch (e) {}
if (!state.dailyGoalProgress || typeof state.dailyGoalProgress !== "object") {
state.dailyGoalProgress = { quizzesCompleted: 0, questionsReviewed: 0 };
}
const lastActive = state.lastActiveDate;
const todayToken = parseISODateToUTCStart(today);
const lastToken = lastActive ? parseISODateToUTCStart(lastActive) : null;
if (lastActive) {
if (todayToken > lastToken + 1) {
state.currentStreak = 0;
state.dailyGoalProgress = { quizzesCompleted: 0, questionsReviewed: 0 };
} else if (lastActive !== today) {
state.dailyGoalProgress = { quizzesCompleted: 0, questionsReviewed: 0 };
}
} else {
state.dailyGoalProgress = { quizzesCompleted: 0, questionsReviewed: 0 };
}
if (!lastActive) {
state.currentStreak = 1;
state.lastActiveDate = today;
} else if (lastActive === today) {
// Same day
} else if (lastToken !== null && todayToken === lastToken + 1) {
state.currentStreak += 1;
state.lastActiveDate = today;
} else {
state.currentStreak = 1;
state.lastActiveDate = today;
}
if (type === "quiz") {
state.dailyGoalProgress.quizzesCompleted += value;
} else if (type === "review") {
state.dailyGoalProgress.questionsReviewed += value;
}
try {
localStorage.setItem(STREAK_KEY, JSON.stringify(state));
} catch (e) {}
if (window.achievements && typeof window.achievements.checkAndNotify === "function") {
window.achievements.checkAndNotify();
}
}
function recordReviewResult({ topicId, scorePct, answeredCount = 0 }) {
if (!topicId) return;
const today = _todayLocalISODate();
const schedule = loadSchedule();
const prev = schedule[topicId] || {};
const prevInterval =
typeof prev.intervalDays === "number" && prev.intervalDays > 0 ? prev.intervalDays : 1;
const pct = typeof scorePct === "number" ? scorePct : 0;
let nextInterval = prevInterval;
if (pct >= 80) {
nextInterval = Math.max(1, Math.round(prevInterval * 2));
} else if (pct >= 50) {
nextInterval = Math.max(1, Math.round(prevInterval * 1.3));
} else {
nextInterval = 1;
}
const nextReviewDate = _addDaysISO(today, nextInterval);
schedule[topicId] = {
intervalDays: nextInterval,
nextReviewDate,
lastReviewedAt: today,
lastScorePct: pct,
lastAnsweredCount: answeredCount,
updatedAt: Date.now(),
};
saveSchedule(schedule);
// Save to chronological history log
const history = loadHistory();
history.unshift({
topicId,
scorePct: pct,
answeredCount,
reviewedAt: today,
timestamp: Date.now()
});
// Keep history reasonably bounded (e.g., last 100 reviews)
if (history.length > 100) {
history.splice(100);
}
saveHistory(history);
// Update unified daily streak & daily goal state
_updateUnifiedStreakAndGoal("review", answeredCount);
return schedule[topicId];
}
function skipTopic(topicId) {
if (!topicId) return;
const today = _todayLocalISODate();
const schedule = loadSchedule();
const prev = schedule[topicId] || {};
// Skip action: postpones review by a fixed interval of +2 days
schedule[topicId] = {
...prev,
intervalDays: 2,
nextReviewDate: _addDaysISO(today, 2),
updatedAt: Date.now()
};
saveSchedule(schedule);
// Dispatch event to re-render UI in real time
window.dispatchEvent(new Event("review-saved"));
}
function _makeQBankQuestion(base) {
const q = { ...base };
// Ensure stable id
if (!q.__qid && typeof q.q === "string") {
q.__qid = `${base.topicId || ""}:${q.q}`;
}
// Normalize fields
if (!Array.isArray(q.options)) q.options = [];
if (typeof q.answerIndex !== "number") q.answerIndex = 0;
if (typeof q.whyWrong !== "string") q.whyWrong = "";
if (!Array.isArray(q.misconceptions)) q.misconceptions = [];
return q;
}
function _getWhyWrongForChoice(question, pickedIndex) {
if (!question) return "";
const whyWrong = typeof question.whyWrong === "string" ? question.whyWrong : "";
return whyWrong || "";
}
// Minimal question set per topic (now enriched with misconception explanations).
function getReviewQuiz(topicId) {
// NOTE: Keep this bank self-contained (hardcoded) because the review UI
// currently relies on this client-side dataset.
const bank = {
"physics-motion": [
{
__qid: "physics-motion:q1",
topicId: "physics-motion",
q: "Which quantity describes how fast an object changes its velocity?",
options: ["Speed", "Acceleration", "Distance", "Momentum"],
answerIndex: 1,
whyWrong: "Acceleration measures the rate of change of velocity (not speed, not distance, and not momentum).",
misconceptions: [
{
title: "Confusing speed with acceleration",
explanation: "Speed tells how fast the motion is (magnitude of velocity). Acceleration tells how the velocity changes (including changes in speed and/or direction).",
commonWrongChoices: ["Speed"],
},
],
remediation: {
prompt: "If an object’s speed is constant but its direction changes, does it have acceleration?",
options: ["No", "Yes", "Only if gravity acts", "Only if it slows down"],
answerIndex: 1,
explanation: "Yes. Any change in velocity—speed or direction—means acceleration.",
},
},
{
__qid: "physics-motion:q2",
q: "If velocity is constant, acceleration is…",
options: ["Constant", "Zero", "Increasing", "Negative"],
answerIndex: 1,
whyWrong: "If velocity is constant, it does not change over time, so acceleration (rate of change of velocity) is zero.",
misconceptions: [
{
title: "Thinking ‘constant velocity’ still implies acceleration",
explanation: "Acceleration comes from changing velocity. Constant velocity means there is no change—so acceleration is zero.",
commonWrongChoices: ["Constant", "Increasing", "Negative"],
},
],
remediation: {
prompt: "Acceleration is the rate of…",
options: ["Change of velocity", "Change of distance", "Change of mass", "Change of temperature"],
answerIndex: 0,
explanation: "Acceleration is the rate of change of velocity.",
},
},
],
"physics-nlm": [
{
q: "Newton's First Law relates to…",
options: ["Motion with constant force", "Inertia and tendency to maintain velocity", "Mutual attractions", "Energy conservation"],
answerIndex: 1,
},
{
q: "Newton's Second Law: F is proportional to…",
options: ["Velocity", "Acceleration", "Mass only", "Distance"],
answerIndex: 1,
},
],
"physics-projectile": [
{
q: "In projectile motion (neglecting air resistance), horizontal acceleration is…",
options: ["Zero", "Constant positive", "Constant negative", "Depends on time"],
answerIndex: 0,
},
{
q: "Vertical motion is influenced by…",
options: ["No forces", "Gravity", "Magnetism", "Friction"],
answerIndex: 1,
},
],
"physics-ray": [
{
q: "When light refracts, it changes direction due to…",
options: ["Different speeds in different media", "Reflection only", "Electric fields", "Mass"],
answerIndex: 0,
},
{
q: "A concave mirror generally…",
options: ["Always forms a virtual image", "Can form real images depending on object position", "Only forms real images", "Cannot focus light"],
answerIndex: 1,
},
],
"maths-calculus": [
{
q: "The derivative of a function represents its…",
options: ["Average value", "Rate of change", "Total distance", "Constant term"],
answerIndex: 1,
},
{
q: "∫ f(x) dx is the…",
options: ["Difference", "Integral/accumulation", "Derivative", "Logarithm"],
answerIndex: 1,
},
],
"maths-vectors": [
{
q: "A vector is defined by…",
options: ["Magnitude only", "Magnitude and direction", "Direction only", "Neither"],
answerIndex: 1,
},
{
q: "The dot product of perpendicular vectors is…",
options: ["1", "0", "-1", "Infinity"],
answerIndex: 1,
},
],
"maths-probability": [
{
q: "Probability values lie in the range…",
options: ["0 to 1", "-1 to 1", "1 to 100", "0 to 100"],
answerIndex: 0,
},
{
q: "If events are independent, then P(A and B) =…",
options: ["P(A)+P(B)", "P(A)×P(B)", "P(A)-P(B)", "1"],
answerIndex: 1,
},
],
"maths-geometry": [
{
q: "Distance formula in coordinate geometry gives the…",
options: ["Length between points", "Slope only", "Area only", "Angle only"],
answerIndex: 0,
},
{
q: "The slope of a line measures its…",
options: ["Steepness", "Length", "Area", "Curvature"],
answerIndex: 0,
},
],
"chemistry-atomic": [
{
q: "The atomic number equals the number of…",
options: ["Neutrons", "Protons", "Electrons only", "Nucleons"],
answerIndex: 1,
},
{
q: "Isotopes have the same…",
options: ["Mass number only", "Number of neutrons", "Atomic number (protons)", "Volume"],
answerIndex: 2,
},
],
"chemistry-bonding": [
{
q: "An ionic bond forms due to…",
options: ["Sharing electrons", "Transfer of electrons", "Unequal mass", "Magnetism"],
answerIndex: 1,
},
{
q: "A covalent bond involves…",
options: ["Transfer of electrons", "Sharing of electrons", "No electrons", "Only ions"],
answerIndex: 1,
},
],
"chemistry-equil": [
{
q: "At equilibrium, the…",
options: ["Reaction stops", "Forward and reverse rates become equal", "Concentrations are always zero", "Temperature is zero"],
answerIndex: 1,
},
{
q: "Le Chatelier's principle helps predict how a system responds to…",
options: ["Only pressure changes", "Perturbations (stress)", "Only colors", "No changes"],
answerIndex: 1,
},
],
"chemistry-thermo": [
{
q: "Thermodynamics primarily studies…",
options: ["Motion", "Heat and energy transformations", "Electricity only", "Sound"],
answerIndex: 1,
},
{
q: "A process is exothermic if it…",
options: ["Absorbs heat", "Releases heat", "Has zero heat", "Always increases temperature"],
answerIndex: 1,
},
],
};
const generic = [
{
q: "Spaced repetition helps by…",
options: ["Remembering less", "Improving long-term recall", "Skipping practice", "Only using notes"],
answerIndex: 1,
},
{
q: "A review should be taken when it’s…",
options: ["Random", "Due / scheduled", "Never", "Only after exams"],
answerIndex: 1,
},
];
return bank[topicId] || generic;
}
function ensureModal() {
const modal = document.getElementById("reviewModal");
if (!modal) return null;
return modal;
}
function renderQuiz({ topicId, topicLabel, retryQids }) {
const modal = ensureModal();
if (!modal) return;
let quiz = getReviewQuiz(topicId);
if (Array.isArray(retryQids) && retryQids.length > 0) {
quiz = retryQids.map(item => {
if (item && typeof item === "object") {
return {
__qid: item.qid,
topicId: topicId,
q: item.q || item.question,
options: item.options,
answerIndex: typeof item.answerIndex === "number" ? item.answerIndex : item.options.indexOf(item.answer),
explanation: item.explanation || ""
};
} else {
return quiz.find(q => q.__qid === item);
}
}).filter(Boolean);
}
const modalTitle = document.getElementById("reviewModalTitle");
const container = document.getElementById("reviewQuizContainer");
const msg = document.getElementById("reviewResultMessage");
const submitBtn = document.getElementById("reviewSubmitBtn");
if (modalTitle) modalTitle.textContent = `Review: ${topicLabel || topicId}`;
if (container) {
container.innerHTML = "";
container.dataset.topicId = topicId;
}
if (msg) msg.textContent = "";
if (!container) return;
quiz.forEach((item, idx) => {
const qWrap = document.createElement("div");
qWrap.className = "review-question";
qWrap.style.marginBottom = "20px";
const h = document.createElement("div");
h.className = "review-question-text";
h.style.fontWeight = "bold";
h.style.fontSize = "1rem";
h.style.marginBottom = "10px";
h.style.color = "var(--text-color)";
h.textContent = `${idx + 1}. ${item.q}`;
const optionsWrap = document.createElement("div");
optionsWrap.className = "review-options";
optionsWrap.style.display = "flex";
optionsWrap.style.flexDirection = "column";
optionsWrap.style.gap = "8px";
item.options.forEach((opt, optIdx) => {
const label = document.createElement("label");
label.style.display = "flex";
label.style.alignItems = "center";
label.style.gap = "10px";
label.style.padding = "10px 12px";
label.style.borderRadius = "6px";
label.style.background = "var(--progress-item-bg)";
label.style.border = "1px solid var(--border-color)";
label.style.cursor = "pointer";
label.style.transition = "var(--theme-transition)";
const radio = document.createElement("input");
radio.type = "radio";
radio.name = `review_q_${idx}`;
radio.value = String(optIdx);
radio.style.cursor = "pointer";
label.appendChild(radio);
label.appendChild(document.createTextNode(` ${opt}`));
// Add visual feedback on click/hover
radio.addEventListener("change", () => {
optionsWrap.querySelectorAll("label").forEach(l => {
l.style.borderColor = "var(--border-color)";
l.style.background = "var(--progress-item-bg)";
});
if (radio.checked) {
label.style.borderColor = "var(--accent-color)";
label.style.background = "rgba(56, 189, 248, 0.08)";
}
});
optionsWrap.appendChild(label);
});
qWrap.appendChild(h);
qWrap.appendChild(optionsWrap);
container.appendChild(qWrap);
});
if (submitBtn) submitBtn.disabled = false;
if (window.openDialog) {
window.openDialog(modal);
} else {
modal.style.display = "block";
}
}
function closeModal() {
const modal = document.getElementById("reviewModal");
if (modal) {
if (window.closeDialog) {
window.closeDialog(modal);
} else {
modal.style.display = "none";
}
}
}
function readQuizAnswers() {
const container = document.getElementById("reviewQuizContainer");
if (!container) return { scorePct: 0, correctCount: 0, total: 0, answeredCount: 0 };
const questions = Array.from(container.querySelectorAll(".review-question"));
const total = questions.length;
const topicId = container.dataset.topicId;
const isRetry = container.dataset.isRetry === "true";
const retryQids = container.dataset.retryQids ? JSON.parse(container.dataset.retryQids) : [];
const quiz = isRetry && retryQids.length > 0
? retryQids.map(item => {
if (item && typeof item === "object") {
return {
__qid: item.qid,
topicId: topicId,
q: item.q || item.question,
options: item.options,
answerIndex: typeof item.answerIndex === "number" ? item.answerIndex : item.options.indexOf(item.answer),
explanation: item.explanation || ""
};
} else {
const fullQuiz = getReviewQuiz(topicId);
return fullQuiz.find(q => q.__qid === item);
}
}).filter(Boolean)
: getReviewQuiz(topicId);
let correctCount = 0;
let answeredCount = 0;
for (let i = 0; i < total; i++) {
const qWrap = questions[i];
const checked = qWrap.querySelector(`input[name="review_q_${i}"]:checked`);
if (!checked) continue;
answeredCount += 1;
const picked = Number(checked.value);
if (picked === quiz[i].answerIndex) correctCount += 1;
}
const scorePct = total > 0 ? Math.round((correctCount / total) * 100) : 0;
return { scorePct, correctCount, total, answeredCount };
}
function start(topicId, options = {}) {
const topicsList = getTopicsList();
const foundTopic = topicsList.find(t => t.id === topicId);
const topicLabel = foundTopic ? foundTopic.label : topicId;
const modal = ensureModal();
const container = document.getElementById("reviewQuizContainer");
if (container) {
container.dataset.topicId = topicId;
if (options.retryQids) {
container.dataset.isRetry = "true";
container.dataset.retryQids = JSON.stringify(options.retryQids);
} else {
delete container.dataset.isRetry;
delete container.dataset.retryQids;
}
}
renderQuiz({ topicId, topicLabel, retryQids: options.retryQids });
const submitBtn = document.getElementById("reviewSubmitBtn");
if (submitBtn) {
submitBtn.onclick = function () {
const isRetry = container.dataset.isRetry === "true";
const retryQids = container.dataset.retryQids ? JSON.parse(container.dataset.retryQids) : [];
// Compute score and update summary
const { scorePct, correctCount, total, answeredCount } = readQuizAnswers();
const msg = document.getElementById("reviewResultMessage");
if (msg) msg.textContent = `Score: ${correctCount}/${total} (${scorePct}%).`;
// Render detailed per‑question results with an Ask button
if (container) {
container.innerHTML = "";
const quiz = isRetry && retryQids.length > 0
? retryQids.map(item => {
if (item && typeof item === "object") {
return {
__qid: item.qid,
topicId: topicId,
q: item.q || item.question,
options: item.options,
answerIndex: typeof item.answerIndex === "number" ? item.answerIndex : item.options.indexOf(item.answer),
explanation: item.explanation || ""
};
} else {
const fullQuiz = getReviewQuiz(topicId);
return fullQuiz.find(q => q.__qid === item);
}
}).filter(Boolean)
: getReviewQuiz(topicId);
const correctedQids = [];
quiz.forEach((item, idx) => {
const qDiv = document.createElement("div");
qDiv.className = "review-question-result";
qDiv.style.marginBottom = "12px";
const selected = document.querySelector(`input[name="review_q_${idx}"]:checked`);
const userIdx = selected ? Number(selected.value) : null;
const userAns = userIdx !== null ? item.options[userIdx] : "<em>No answer</em>";
const correct = userIdx === item.answerIndex;
if (correct) {
correctedQids.push(item.__qid);
}
const whyWrongText =
typeof item.whyWrong === "string" && item.whyWrong.trim()
? item.whyWrong.trim()
: "";
const remediationExplanation =
item.remediation && typeof item.remediation.explanation === "string"
? item.remediation.explanation.trim()
: "";
const misconceptionExplanation =
Array.isArray(item.misconceptions) && item.misconceptions[0]
? typeof item.misconceptions[0].explanation === "string"
? item.misconceptions[0].explanation.trim()
: ""
: "";
const explanationCorrect = remediationExplanation || "";
const explanationWrong = whyWrongText || misconceptionExplanation || "";
const explanationPicked = correct ? explanationCorrect : explanationWrong;
qDiv.innerHTML = `
<div><strong>Q${idx + 1}:</strong> ${item.q}</div>
<div>Your answer: ${userAns} ${correct ? "✅" : "❌"}</div>
<div>Correct answer: ${item.options[item.answerIndex]}</div>
${explanationPicked
? `
<div class="explanation-panel ${correct ? "explanation-correct" : "explanation-wrong"}">
<div class="explanation-title">${correct ? "Why this is correct" : "Why this is wrong"}</div>
<div class="explanation-body">${explanationPicked}</div>
</div>
`
: ""}
`;
const askBtn = document.createElement("button");
askBtn.textContent = "Ask about this question";
askBtn.className = "action-btn";
askBtn.style.marginTop = "6px";
askBtn.onclick = () => {
fetch("/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: `Help me understand this question: ${item.q}` })
})
.then(res => res.json())
.then(data => {
alert(data.reply || "No reply");
})
.catch(err => {
console.error(err);
alert("Error contacting chatbot");
});
};
qDiv.appendChild(askBtn);
container.appendChild(qDiv);
});
// If retry mode, update missed list
if (isRetry && correctedQids.length > 0) {
const MISSED_KEY = "learnsphere_review_missed_v1";
let map = {};
try {
map = JSON.parse(localStorage.getItem(MISSED_KEY)) || {};
} catch (e) {}
if (map[topicId] && Array.isArray(map[topicId].missedQids)) {
map[topicId].missedQids = map[topicId].missedQids.filter(item => {
const qid = (item && typeof item === "object") ? item.qid : item;
return !correctedQids.includes(qid);
});
map[topicId].updatedAt = Date.now();
try {
localStorage.setItem(MISSED_KEY, JSON.stringify(map));
} catch (e) {}
}
window.dispatchEvent(new Event("review-mistakes-retried"));
}
}
// Persist the review result only if NOT in retry mode
if (!isRetry) {
recordReviewResult({ topicId, scorePct, answeredCount });
}
// Disable button to prevent double submission
submitBtn.disabled = true;
setTimeout(() => {
closeModal();
window.dispatchEvent(new Event("review-saved"));
}, 800);
};
}
}
// ─── Dashboard Render Logic ────────────────────────────────────────────────
function initDashboard() {
const dueListEl = document.getElementById("due-list");
if (!dueListEl) return; // Not on review.html
const schedule = loadSchedule();
const today = _todayLocalISODate();
const todayToken = _parseISODateToUTCStart(today);
let progressMap = {};
try {
progressMap = JSON.parse(localStorage.getItem("learnsphere_progress")) || {};
} catch {}
const topicsList = getTopicsList();
const dueTopics = [];
const upcomingTopics = [];
topicsList.forEach(topic => {
const s = schedule[topic.id];
const prog = progressMap[topic.id] || "not-started";
if (s && s.nextReviewDate) {
const nextToken = _parseISODateToUTCStart(s.nextReviewDate);
if (todayToken >= nextToken) {
dueTopics.push({ topic, schedule: s, isDue: true });
} else {
upcomingTopics.push({ topic, schedule: s, isDue: false });
}
} else {
// Never reviewed: if completed or in-progress, consider it due today
if (prog === "completed" || prog === "in-progress") {
dueTopics.push({ topic, schedule: null, isDue: true });
} else {
upcomingTopics.push({ topic, schedule: null, isDue: false });
}
}
});
// Sort upcoming: scheduled ones first (sorted by soonest date), unscheduled last
upcomingTopics.sort((a, b) => {
if (a.schedule && b.schedule) {
return _parseISODateToUTCStart(a.schedule.nextReviewDate) - _parseISODateToUTCStart(b.schedule.nextReviewDate);
}
if (a.schedule) return -1;
if (b.schedule) return 1;
return 0;
});
// Render Stats
const statsDueEl = document.getElementById("stats-due-count");
if (statsDueEl) statsDueEl.textContent = String(dueTopics.length);
let totalScore = 0;
let reviewedCount = 0;
for (const id in schedule) {
const s = schedule[id];
if (s && typeof s.lastScorePct === "number" && s.lastReviewedAt) {
totalScore += s.lastScorePct;
reviewedCount += 1;
}
}
const avgAccuracyEl = document.getElementById("stats-accuracy-average");
if (avgAccuracyEl) {
avgAccuracyEl.textContent = reviewedCount > 0 ? `${Math.round(totalScore / reviewedCount)}%` : "—";
}
const history = loadHistory();
const totalReviewsEl = document.getElementById("stats-total-reviews");
if (totalReviewsEl) totalReviewsEl.textContent = String(history.length);
// Render Due Today List
dueListEl.innerHTML = "";
if (dueTopics.length === 0) {
dueListEl.innerHTML = `
<div class="empty-state">
<span class="empty-state-icon">🎉</span>
No reviews due today! Keep up the good work.
</div>
`;
} else {
dueTopics.forEach(({ topic, schedule: s }) => {
const item = document.createElement("div");
item.className = "review-item";
let metaText = "Never reviewed";
if (s && s.lastReviewedAt) {
metaText = `Last reviewed: ${s.lastReviewedAt} (${s.lastScorePct}% score)`;
}
item.innerHTML = `
<div class="item-details">
<div class="item-title">${topic.label}</div>
<div class="item-meta">
<span class="badge-subject">${topic.subject}</span>
<span>•</span>
<span>${metaText}</span>
</div>
</div>
<div class="item-actions">
<button class="action-btn skip" data-id="${topic.id}" title="Postpone review by 2 days">Skip for now</button>
<button class="action-btn start" data-id="${topic.id}">Review Now</button>
</div>
`;
// Bind buttons
item.querySelector(".action-btn.start").addEventListener("click", () => {
start(topic.id);
});
item.querySelector(".action-btn.skip").addEventListener("click", () => {
skipTopic(topic.id);
});
dueListEl.appendChild(item);
});
}
// Render Upcoming List
const upcomingListEl = document.getElementById("upcoming-list");
if (upcomingListEl) {
upcomingListEl.innerHTML = "";
if (upcomingTopics.length === 0) {
upcomingListEl.innerHTML = `
<div class="empty-state">
No reviews scheduled yet. Complete topics to start getting review sessions.
</div>
`;
} else {
upcomingTopics.forEach(({ topic, schedule: s }) => {
const item = document.createElement("div");
item.className = "review-item";
let metaText = "Unscheduled — Start reviewing to build streak";
let actionText = "Start Review";
if (s && s.nextReviewDate) {
const todayToken = _parseISODateToUTCStart(_todayLocalISODate());
const nextToken = _parseISODateToUTCStart(s.nextReviewDate);
const delta = nextToken - todayToken;
const daysLeft = delta <= 0 ? "Today" : `${delta}d`;
metaText = `Scheduled: Review in ${daysLeft} (${s.nextReviewDate})`;
actionText = "Review Early";
}
item.innerHTML = `
<div class="item-details">
<div class="item-title">${topic.label}</div>
<div class="item-meta">
<span class="badge-subject">${topic.subject}</span>
<span>•</span>
<span>${metaText}</span>
</div>
</div>
<div class="item-actions">
<button class="action-btn start" style="background:var(--btn-secondary-bg); color:var(--text-color); border:1px solid var(--border-color);" data-id="${topic.id}">${actionText}</button>
</div>
`;
item.querySelector(".action-btn.start").addEventListener("click", () => {
start(topic.id);
});
upcomingListEl.appendChild(item);
});
}
}
// Render Timeline / History List
const historyListEl = document.getElementById("history-list");
if (historyListEl) {
historyListEl.innerHTML = "";
if (history.length === 0) {
historyListEl.innerHTML = `
<div class="empty-state" style="padding: 15px 0;">
No reviews completed yet. Start review on a topic to see history.
</div>
`;
historyListEl.style.borderLeft = "none";
historyListEl.style.paddingLeft = "0";
} else {
historyListEl.style.borderLeft = "2px solid var(--border-color)";
historyListEl.style.paddingLeft = "20px";
history.forEach(item => {
const found = topicsList.find(t => t.id === item.topicId);
const label = found ? found.label : item.topicId;
const event = document.createElement("div");
event.className = "timeline-event";
const pct = item.scorePct;
let color = "var(--completed-color)";
if (pct < 50) color = "#ef4444";
else if (pct < 80) color = "var(--in-progress-color)";