-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathprogress.js
More file actions
429 lines (358 loc) · 16.8 KB
/
Copy pathprogress.js
File metadata and controls
429 lines (358 loc) · 16.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
/**
* progress.js — LearnSphere Study Progress Tracker
*
* Manages topic-level progress states (Not Started → In Progress → Completed)
* using localStorage for persistence across sessions.
*
* Usage: Include this script on home.html (or any page with #progressList).
*/
// ── Data ──────────────────────────────────────────────────────────────────────
/** @type {Array<{id: string, label: string, subject: string}>} */
const TOPICS = [
{ id: "physics-motion", label: "Physics: Motion", subject: "physics" },
{ id: "physics-nlm", label: "Physics: Newton's Laws of Motion", subject: "physics" },
{ id: "physics-projectile", label: "Physics: Projectile Motion", subject: "physics" },
{ id: "physics-ray", label: "Physics: Ray Optics", subject: "physics" },
{ id: "maths-calculus", label: "Maths: Calculus", subject: "maths" },
{ id: "maths-vectors", label: "Maths: Vectors & 3D Geometry", subject: "maths" },
{ id: "maths-probability", label: "Maths: Probability & Statistics", subject: "maths" },
{ id: "maths-geometry", label: "Maths: Coordinate Geometry", subject: "maths" },
{ id: "chemistry-atomic", label: "Chemistry: Atomic Structure", subject: "chemistry" },
{ id: "chemistry-bonding", label: "Chemistry: Chemical Bonding", subject: "chemistry" },
{ id: "chemistry-equil", label: "Chemistry: Equilibrium", subject: "chemistry" },
{ id: "chemistry-thermo", label: "Chemistry: Thermodynamics", subject: "chemistry" },
];
const STATES = ["not-started", "in-progress", "completed"];
const STATE_LABELS = {
"not-started": "Not Started",
"in-progress": "In Progress",
"completed": "Completed ✅",
};
const STATE_COLORS = {
"not-started": "#888",
"in-progress": "#f0a500",
"completed": "#66fcf1",
};
const STORAGE_KEY = "learnsphere_progress";
// XP system constants
const XP_PER_LEVEL = 1000; // XP required per level
const REVIEW_SCHEDULE_KEY = "learnsphere_review_schedule_v1";
// ── Storage Helpers ───────────────────────────────────────────────────────────
function loadProgress() {
try {
const data = JSON.parse(localStorage.getItem(STORAGE_KEY)) || {};
// Ensure XP and level fields exist
if (typeof data.xp !== "number") data.xp = 0;
if (typeof data.level !== "number") data.level = 0;
return data;
} catch {
return { xp: 0, level: 0 };
}
}
// Helper to calculate level from XP
function calculateLevel(xp) {
if (typeof xp !== "number" || xp < 0) return 0;
return Math.floor(xp / XP_PER_LEVEL);
}
function loadReviewSchedule() {
try {
return JSON.parse(localStorage.getItem(REVIEW_SCHEDULE_KEY)) || {};
} catch {
return {};
}
}
function saveReviewSchedule(scheduleMap) {
try {
localStorage.setItem(REVIEW_SCHEDULE_KEY, JSON.stringify(scheduleMap));
} catch (e) {
console.warn("LearnSphere: Could not save review schedule.", e);
}
}
function saveProgress(progressMap) {
try {
// Ensure XP and level are persisted
if (typeof progressMap.xp !== "number") progressMap.xp = 0;
if (typeof progressMap.level !== "number") progressMap.level = 0;
localStorage.setItem(STORAGE_KEY, JSON.stringify(progressMap));
} catch (e) {
console.warn("LearnSphere: Could not save progress to localStorage.", e);
}
}
function getTopicState(progressMap, topicId) {
return progressMap[topicId] || "not-started";
}
function cycleState(currentState) {
const idx = STATES.indexOf(currentState);
return STATES[(idx + 1) % STATES.length];
}
// ── Spaced Repetition Helpers ───────────────────────────────────────────────
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}`;
}
function getReviewScheduleForTopic(topicId) {
const scheduleMap = loadReviewSchedule();
return scheduleMap[topicId] || null;
}
function getReviewStatus(topicId) {
const s = getReviewScheduleForTopic(topicId);
const today = _todayLocalISODate();
const todayToken = _parseISODateToUTCStart(today);
if (!s || !s.nextReviewDate) {
return { due: false, nextReviewDate: null, intervalDays: null, lastReviewedAt: null };
}
const nextToken = _parseISODateToUTCStart(s.nextReviewDate);
const due = todayToken >= nextToken;
return {
due,
nextReviewDate: s.nextReviewDate,
intervalDays: typeof s.intervalDays === "number" ? s.intervalDays : null,
lastReviewedAt: s.lastReviewedAt || null,
scoreLast: typeof s.lastScorePct === "number" ? s.lastScorePct : null,
};
}
function recordReviewResult({ topicId, scorePct, answeredCount = 0 }) {
if (!topicId) return;
const scheduleMap = loadReviewSchedule();
const today = _todayLocalISODate();
const prev = scheduleMap[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);
scheduleMap[topicId] = {
intervalDays: nextInterval,
nextReviewDate,
lastReviewedAt: today,
lastScorePct: pct,
lastAnsweredCount: answeredCount,
updatedAt: Date.now(),
};
saveReviewSchedule(scheduleMap);
if (window.studyProgress && typeof window.studyProgress.recordActivity === "function") {
window.studyProgress.recordActivity("review", answeredCount);
}
return scheduleMap[topicId];
}
function formatDaysUntil(isoDate) {
if (!isoDate) return "";
const todayToken = _parseISODateToUTCStart(_todayLocalISODate());
const nextToken = _parseISODateToUTCStart(isoDate);
const delta = nextToken - todayToken;
if (delta <= 0) return "0d";
return `${delta}d`;
}
// ── Rendering ─────────────────────────────────────────────────────────────────
function renderProgressList() {
const list = document.getElementById("progressList");
if (!list) return;
const progressMap = loadProgress();
list.innerHTML = ""; // Clear static placeholder items
TOPICS.forEach(topic => {
const state = getTopicState(progressMap, topic.id);
const li = document.createElement("li");
li.className = `progress-item progress-${state}`;
li.setAttribute("data-topic-id", topic.id);
const label = document.createElement("span");
label.className = "progress-label";
label.textContent = topic.label;
const badge = document.createElement("button");
badge.className = "progress-badge";
badge.textContent = STATE_LABELS[state];
badge.style.color = STATE_COLORS[state];
// ── Review CTA ───────────────────────────────────────────────────────
const reviewBtn = document.createElement("button");
reviewBtn.className = "review-badge";
const reviewStatus = getReviewStatus(topic.id);
const isDue = !!reviewStatus.due;
reviewBtn.disabled = !isDue;
if (!reviewStatus.nextReviewDate) {
// Not scheduled yet: let user review once they start.
reviewBtn.disabled = false;
reviewBtn.textContent = "Review";
} else {
reviewBtn.textContent = isDue ? "Review" : `Review in ${formatDaysUntil(reviewStatus.nextReviewDate)}`;
}
// Basic styling; assumes CSS may not exist yet.
reviewBtn.style.marginLeft = "10px";
reviewBtn.style.padding = "6px 12px";
reviewBtn.style.borderRadius = "20px";
reviewBtn.style.border = isDue ? "1px solid var(--accent-color)" : "1px solid rgba(255,255,255,0.18)";
reviewBtn.style.background = isDue ? "rgba(102,252,241,0.12)" : "rgba(255,255,255,0.04)";
reviewBtn.style.color = isDue ? "var(--accent-color)" : "rgba(255,255,255,0.55)";
reviewBtn.style.fontWeight = "700";
reviewBtn.style.cursor = isDue ? "pointer" : "not-allowed";
reviewBtn.addEventListener("click", () => {
window.location.href = `review.html?topic=${topic.id}`;
});
badge.setAttribute("aria-label", `${topic.label}: ${STATE_LABELS[state]}. Click to change status.`);
badge.setAttribute("title", "Click to cycle: Not Started → In Progress → Completed");
badge.addEventListener("click", () => {
const current = getTopicState(loadProgress(), topic.id);
const next = cycleState(current);
const updated = loadProgress();
updated[topic.id] = next;
saveProgress(updated);
renderProgressList(); // Re-render to reflect change
updateProgressSummary(); // Update summary bar
});
li.appendChild(label);
li.appendChild(badge);
li.appendChild(reviewBtn);
list.appendChild(li);
});
}
/** Render overall completion percentage bar */
function updateProgressSummary() {
const summaryEl = document.getElementById("progress-summary");
const barEl = document.getElementById("progress-bar-fill");
if (!summaryEl || !barEl) return;
const progressMap = loadProgress();
const completed = TOPICS.filter(t => progressMap[t.id] === "completed").length;
const pct = Math.round((completed / TOPICS.length) * 100);
barEl.style.width = pct + "%";
barEl.setAttribute("aria-valuenow", pct);
summaryEl.textContent = `${completed} of ${TOPICS.length} topics completed (${pct}%)`;
}
// ── Unified Streaks & Daily Goals API ─────────────────────────────────────────
window.studyProgress = {
STREAK_KEY: "learnsphere_streak_state_v1",
// XP related helpers
addXP(amount) {
const progress = loadProgress();
const inc = Number(amount) || 0;
progress.xp = (progress.xp || 0) + inc;
progress.level = calculateLevel(progress.xp);
saveProgress(progress);
},
getXP() { return (loadProgress().xp) || 0; },
getLevel() { return (loadProgress().level) || 0; },
XP_PER_LEVEL,
loadStreakState() {
try {
const raw = localStorage.getItem(this.STREAK_KEY);
if (!raw) return { lastActiveDate: null, currentStreak: 0, dailyGoalProgress: { quizzesCompleted: 0, questionsReviewed: 0 } };
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== "object") {
return { lastActiveDate: null, currentStreak: 0, dailyGoalProgress: { quizzesCompleted: 0, questionsReviewed: 0 } };
}
if (!parsed.dailyGoalProgress || typeof parsed.dailyGoalProgress !== "object") {
parsed.dailyGoalProgress = { quizzesCompleted: 0, questionsReviewed: 0 };
}
const today = _todayLocalISODate();
if (parsed.lastActiveDate) {
const todayToken = _parseISODateToUTCStart(today);
const lastToken = _parseISODateToUTCStart(parsed.lastActiveDate);
if (todayToken > lastToken + 1) {
parsed.currentStreak = 0;
}
if (parsed.lastActiveDate !== today) {
parsed.dailyGoalProgress = { quizzesCompleted: 0, questionsReviewed: 0 };
}
} else {
parsed.dailyGoalProgress = { quizzesCompleted: 0, questionsReviewed: 0 };
}
return parsed;
} catch {
return { lastActiveDate: null, currentStreak: 0, dailyGoalProgress: { quizzesCompleted: 0, questionsReviewed: 0 } };
}
},
saveStreakState(state) {
try {
localStorage.setItem(this.STREAK_KEY, JSON.stringify(state));
} catch (e) {
console.warn("LearnSphere: Could not save streak state.", e);
}
},
recordActivity(type, value = 1) {
const today = _todayLocalISODate();
const state = this.loadStreakState();
const lastActive = state.lastActiveDate;
const todayToken = _parseISODateToUTCStart(today);
const lastToken = lastActive ? _parseISODateToUTCStart(lastActive) : null;
const prevStreak = state.currentStreak || 0;
if (!lastActive) {
state.currentStreak = 1;
state.lastActiveDate = today;
state.dailyGoalProgress = { quizzesCompleted: 0, questionsReviewed: 0 };
} else if (lastActive === today) {
// Already active today, no change to streak date or count
} else if (lastToken !== null && todayToken === lastToken + 1) {
state.currentStreak += 1;
state.lastActiveDate = today;
state.dailyGoalProgress = { quizzesCompleted: 0, questionsReviewed: 0 };
} else {
state.currentStreak = 1;
state.lastActiveDate = today;
state.dailyGoalProgress = { quizzesCompleted: 0, questionsReviewed: 0 };
}
if (type === "quiz") {
state.dailyGoalProgress.quizzesCompleted += value;
} else if (type === "review") {
state.dailyGoalProgress.questionsReviewed += value;
}
this.saveStreakState(state);
// Milestone notifications (best-effort)
try {
if (window.notifications && typeof window.notifications.notifyFromEvent === "function") {
const qDone = state.dailyGoalProgress.quizzesCompleted || 0;
const rDone = state.dailyGoalProgress.questionsReviewed || 0;
const goalAchieved = qDone >= 1 || rDone >= 10;
// Fire streak maintained when streak increases (and user is active today)
if ((state.currentStreak || 0) > prevStreak) {
const dedupeKey = `streak-up-${today}-${state.currentStreak}`;
window.notifications.notifyFromEvent({
type: "streak",
title: "Streak maintained",
message: `🔥 Streak maintained — you reached a ${state.currentStreak}-day streak!`,
ctaUrl: "my_progress.html",
dedupeKey,
});
} else if (goalAchieved) {
// Also notify for daily goal completion (even if streak didn't increase)
const dedupeKey = `daily-goal-${today}-${qDone}-${rDone}`;
window.notifications.notifyFromEvent({
type: "streak",
title: "Streak maintained",
message: `🎯 Daily goal achieved today. Keep your streak alive!`,
ctaUrl: "my_progress.html",
dedupeKey,
});
}
}
} catch {}
if (window.achievements && typeof window.achievements.checkAndNotify === "function") {
window.achievements.checkAndNotify();
}
return state;
}
};
// ── Init ──────────────────────────────────────────────────────────────────────
document.addEventListener("DOMContentLoaded", () => {
renderProgressList();
updateProgressSummary();
});