-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathexportProgress.js
More file actions
607 lines (543 loc) · 21.1 KB
/
Copy pathexportProgress.js
File metadata and controls
607 lines (543 loc) · 21.1 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
/**
* exportProgress.js — Progress Export (local JSON; ready for backend later)
*
* Collects learner/mastery insights from existing analytics modules:
* - window.quizProgress (quiz analytics + localStorage-backed attempt aggregates)
* - window.studyProgress (streak + daily goal)
*/
(function () {
const quizUtils = (typeof window !== 'undefined' && window.quizUtils) ||
(typeof require !== 'undefined' && require('./quizUtils.js')) ||
(typeof globalThis !== 'undefined' && globalThis.quizUtils) ||
{
aggregateQuizHistory(attempts) {
function safeNumber(n) {
const x = Number(n);
return Number.isFinite(x) ? x : null;
}
const totalAttempts = attempts.length;
let firstAttemptAt = null;
let lastAttemptAt = null;
const byTopicMap = new Map();
for (const a of attempts) {
const started = a?.startedAt;
const finished = a?.finishedAt;
const at = typeof finished === "number" && Number.isFinite(finished) ? finished : (typeof started === "number" && Number.isFinite(started) ? started : null);
if (at != null) {
if (firstAttemptAt == null || at < firstAttemptAt) firstAttemptAt = at;
if (lastAttemptAt == null || at > lastAttemptAt) lastAttemptAt = at;
}
const topicId = a?.topicId || null;
if (!topicId) continue;
if (!byTopicMap.has(topicId)) {
byTopicMap.set(topicId, {
topicId,
quizAttemptCount: 0,
questionsAttempted: 0,
correctCount: 0,
accuracy: null
});
}
const bucket = byTopicMap.get(topicId);
const totalQ = safeNumber(a?.totalQuestions) ?? 0;
const correctCount = (a?.correctCount == null) ? null : safeNumber(a?.correctCount);
bucket.quizAttemptCount += 1;
bucket.questionsAttempted += totalQ;
if (correctCount != null) bucket.correctCount += correctCount;
}
const byTopic = Array.from(byTopicMap.values()).map(b => {
if (b.questionsAttempted > 0 && b.correctCount != null) {
b.accuracy = b.correctCount / b.questionsAttempted;
}
return {
topicId: b.topicId,
quizAttemptCount: b.quizAttemptCount,
questionsAttempted: b.questionsAttempted,
correctCount: Number.isFinite(b.correctCount) ? b.correctCount : 0,
accuracy: b.accuracy
};
}).sort((x, y) => y.quizAttemptCount - x.quizAttemptCount);
const attemptsPreview = attempts
.slice(-25)
.map(a => ({
topicId: a?.topicId || null,
quizId: a?.quizId || null,
practiceDate: a?.practiceDate || null,
startedAt: a?.startedAt ?? null,
finishedAt: a?.finishedAt ?? null,
totalQuestions: safeNumber(a?.totalQuestions) ?? null,
correctCount: (a?.correctCount == null) ? null : safeNumber(a?.correctCount),
accuracy: (a?.accuracy == null) ? null : safeNumber(a?.accuracy),
score: safeNumber(a?.score) ?? null,
timeTakenMs: (a?.timeTakenMs == null) ? null : safeNumber(a?.timeTakenMs)
}));
return {
totalAttempts,
firstAttemptAt,
lastAttemptAt,
byTopic,
attempts: attemptsPreview
};
}
};
function safeNumber(n) {
const x = Number(n);
return Number.isFinite(x) ? x : null;
}
function isoNow() {
return new Date().toISOString();
}
function getStreak() {
try {
if (window.studyProgress && typeof window.studyProgress.loadStreakState === "function") {
const s = window.studyProgress.loadStreakState();
return {
currentStreak: safeNumber(s.currentStreak) ?? 0,
lastActiveDate: s.lastActiveDate || null,
dailyGoalProgress: {
quizzesCompleted: safeNumber(s.dailyGoalProgress?.quizzesCompleted) ?? 0,
questionsReviewed: safeNumber(s.dailyGoalProgress?.questionsReviewed) ?? 0,
},
source: "studyProgress"
};
}
} catch {}
try {
const s = window.quizProgress?.getStreak?.();
if (s) {
return {
currentStreak: safeNumber(s.currentStreak) ?? 0,
lastActiveDate: s.lastPracticeDate || null,
dailyGoalProgress: null,
source: "quizProgress"
};
}
} catch {}
return {
currentStreak: 0,
lastActiveDate: null,
dailyGoalProgress: null,
source: "none"
};
}
function getQuizHistorySummary() {
// From quizProgress localStorage attempts array.
// quizProgress.js stores under: "learnsphere_quiz_progress_v1"
// attempts items include: topicId, quizId, score, totalQuestions, correctCount, practiceDate, accuracy, timeTakenMs, finishedAt
try {
const raw = localStorage.getItem("learnsphere_quiz_progress_v1");
if (!raw) {
return {
totalAttempts: 0,
firstAttemptAt: null,
lastAttemptAt: null,
byTopic: [],
attempts: []
};
}
const parsed = JSON.parse(raw);
const attempts = Array.isArray(parsed?.attempts) ? parsed.attempts : [];
return quizUtils.aggregateQuizHistory(attempts);
} catch {
return {
totalAttempts: 0,
firstAttemptAt: null,
lastAttemptAt: null,
byTopic: [],
attempts: []
};
}
}
function getMasterySnapshot() {
// quizProgress.getMasteryStats returns { [skillId]: { attempts, correct, ... } }
try {
const mastery = window.quizProgress?.getMasteryStats?.() || {};
const taxonomy = window.quizProgress?.SKILL_TAXONOMY || {};
// Convert taxonomy to an indexed list for stable output.
const outSkills = [];
const seen = new Set();
for (const [_, tax] of Object.entries(taxonomy)) {
if (!tax?.skillId || seen.has(tax.skillId)) continue;
seen.add(tax.skillId);
const m = mastery[tax.skillId] || {};
const attempts = safeNumber(m.attempts) ?? 0;
const correct = safeNumber(m.correct) ?? 0;
const accuracy = attempts > 0 ? (correct / attempts) : null;
outSkills.push({
skillId: tax.skillId,
label: tax.label || tax.skillId,
topicId: tax.topicId || null,
quizUrl: tax.quizUrl || null,
attempts,
correct,
accuracy
});
}
// Also include any mastery entries not in taxonomy.
for (const [skillId, m] of Object.entries(mastery)) {
if (seen.has(skillId)) continue;
const attempts = safeNumber(m?.attempts) ?? 0;
const correct = safeNumber(m?.correct) ?? 0;
const accuracy = attempts > 0 ? (correct / attempts) : null;
outSkills.push({
skillId,
label: String(skillId),
topicId: null,
quizUrl: null,
attempts,
correct,
accuracy
});
}
outSkills.sort((a, b) => (b.attempts - a.attempts) || String(a.label).localeCompare(String(b.label)));
return {
totalSkills: outSkills.length,
skills: outSkills
};
} catch {
return { totalSkills: 0, skills: [] };
}
}
function getTopicPerformanceSummary() {
try {
const byTopic = window.quizProgress?.getAllTopicStats?.() || {};
const topics = window.quizProgress?.QUIZ_TOPICS || [];
// Ensure stable ordering using topic registry.
const out = [];
const seenIds = new Set();
for (const t of topics) {
const agg = byTopic[t.id] || null;
const attempts = safeNumber(agg?.attempts) ?? 0;
const qTotal = safeNumber(agg?.questionsTotal) ?? 0;
const correctTotal = safeNumber(agg?.correctTotal) ?? 0;
const accuracy = qTotal > 0 ? (correctTotal / qTotal) : null;
out.push({
topicId: t.id,
label: t.label,
subject: t.subject || null,
attempts,
questionsTotal: qTotal,
correctTotal,
accuracy
});
seenIds.add(t.id);
}
// Include any unknown topic ids in localStorage.
for (const [topicId, agg] of Object.entries(byTopic)) {
if (seenIds.has(topicId)) continue;
const attempts = safeNumber(agg?.attempts) ?? 0;
const qTotal = safeNumber(agg?.questionsTotal) ?? 0;
const correctTotal = safeNumber(agg?.correctTotal) ?? 0;
const accuracy = qTotal > 0 ? (correctTotal / qTotal) : null;
out.push({
topicId,
label: topicId,
subject: null,
attempts,
questionsTotal: qTotal,
correctTotal,
accuracy
});
}
out.sort((a, b) => (b.attempts - a.attempts) || String(a.topicId).localeCompare(String(b.topicId)));
return out;
} catch {
return [];
}
}
function getAccuracyTrend(days = 14) {
try {
const series = window.quizProgress?.getAccuracySeries?.({ days }) || null;
if (!series || !Array.isArray(series.labels) || !Array.isArray(series.accuracyByDay)) {
return {
days,
labels: [],
accuracyByDay: []
};
}
return {
days,
labels: series.labels,
accuracyByDay: series.accuracyByDay
};
} catch {
return { days, labels: [], accuracyByDay: [] };
}
}
/**
* JSON Schema (conceptual; enforced by stable keys rather than full JSON schema validation).
*
* {
* version: { major, minor },
* generatedAt: ISO8601 string,
* format: { type: "progress-export", format: "json" },
* learner: {
* id: string|null,
* roleContext: "teacher"|"parent"|"learner"|"unknown",
* timezone: string|null
* },
* metrics: {
* overallAccuracy: { accuracy: number|null, correct: number, total: number },
* streak: { currentStreak: number, lastActiveDate: string|null, dailyGoalProgress: {...}|null },
* dailyGoal: { quizzesCompleted: number, questionsReviewed: number },
* accuracyTrend: { days: number, labels: string[], accuracyByDay: (number|null)[] },
* mastery: { totalSkills: number, skills: [ {skillId, label, topicId, quizUrl, attempts, correct, accuracy} ] },
* topicPerformance: [ {topicId, label, subject, attempts, questionsTotal, correctTotal, accuracy} ],
* quizHistory: { totalAttempts, firstAttemptAt, lastAttemptAt, byTopic: [...], attempts: [...] }
* },
* client: { app: "LearnSphere", exportId: string }
* }
*/
function buildProgressExportPayload({ formatVersion = { major: 1, minor: 0 }, roleContext = "unknown" } = {}) {
const overall = (() => {
try {
const o = window.quizProgress?.getOverallAccuracy?.();
return {
accuracy: (o?.accuracy == null) ? null : safeNumber(o.accuracy),
correct: safeNumber(o?.correct) ?? 0,
total: safeNumber(o?.total) ?? 0
};
} catch {
return { accuracy: null, correct: 0, total: 0 };
}
})();
const streak = getStreak();
// Normalize dailyGoal into metrics.dailyGoal (even if streak source is quizProgress).
const dailyGoal = {
quizzesCompleted: safeNumber(streak?.dailyGoalProgress?.quizzesCompleted) ?? 0,
questionsReviewed: safeNumber(streak?.dailyGoalProgress?.questionsReviewed) ?? 0
};
const payload = {
version: {
major: Number(formatVersion?.major ?? 1),
minor: Number(formatVersion?.minor ?? 0)
},
generatedAt: isoNow(),
format: {
type: "progress-export",
format: "json"
},
learner: {
id: null,
roleContext,
timezone: Intl?.DateTimeFormat?.().resolvedOptions?.().timeZone || null
},
metrics: {
overallAccuracy: overall,
streak,
dailyGoal,
accuracyTrend: getAccuracyTrend(14),
mastery: getMasterySnapshot(),
topicPerformance: getTopicPerformanceSummary(),
quizHistory: getQuizHistorySummary()
},
client: {
app: "LearnSphere",
exportId: `export_${Date.now()}_${Math.random().toString(16).slice(2)}`
}
};
return payload;
}
function downloadJson(payload, filename = "learnsphere_progress_export.json") {
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 5000);
}
/* ── CSV Export ────────────────────────────────────────────── */
/**
* Escape a value for CSV (RFC 4180).
*/
function csvEscape(val) {
if (val == null) return "";
const str = String(val);
if (str.includes('"') || str.includes(',') || str.includes('\n') || str.includes('\r')) {
return '"' + str.replace(/"/g, '""') + '"';
}
return str;
}
/**
* Build CSV string from the export payload.
* Schema: Date, Quiz, Score (%), Correct, Total Questions, Topics, Time (s)
*/
function buildCsvString(payload) {
const attempts = payload?.metrics?.quizHistory?.attempts || [];
const topicPerf = payload?.metrics?.topicPerformance || [];
// Build topic label lookup
const topicLabelMap = {};
topicPerf.forEach(t => { topicLabelMap[t.topicId] = t.label || t.topicId; });
const header = ["Date", "Quiz", "Score (%)", "Correct", "Total Questions", "Topic", "Time (s)"];
const rows = [header.map(csvEscape).join(",")];
attempts.forEach(a => {
const date = a.practiceDate || (a.finishedAt ? new Date(a.finishedAt).toISOString().slice(0, 10) : "");
const quiz = a.quizId || "";
const scorePct = a.accuracy != null ? Math.round(a.accuracy * 100) : (a.score != null ? a.score : "");
const correct = a.correctCount != null ? a.correctCount : "";
const totalQ = a.totalQuestions != null ? a.totalQuestions : "";
const topic = topicLabelMap[a.topicId] || a.topicId || "";
const timeSec = a.timeTakenMs != null ? Math.round(a.timeTakenMs / 1000) : "";
rows.push([
csvEscape(date),
csvEscape(quiz),
csvEscape(scorePct),
csvEscape(correct),
csvEscape(totalQ),
csvEscape(topic),
csvEscape(timeSec)
].join(","));
});
return rows.join("\r\n");
}
/**
* Download the CSV file.
*/
function downloadCsv(payload, filename = "learnsphere_progress_export.csv") {
const csvString = buildCsvString(payload);
const blob = new Blob([csvString], { type: "text/csv;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 5000);
}
/* ── Shareable Snapshot URL ───────────────────────────────── */
/**
* Create a shareable snapshot and return its URL.
* Stores the snapshot in localStorage keyed by ID.
* The URL contains ?snapshot=<id> which can be opened in the same browser
* (or on any machine that has the snapshot in localStorage — ready for backend).
*/
async function createShareableSnapshot() {
const exportId = await generateSnapshot();
// Build the shareable URL using the current page location
const base = window.location.href.split("?")[0].split("#")[0];
const shareUrl = `${base}?snapshot=${encodeURIComponent(exportId)}`;
return { exportId, shareUrl };
}
/**
* Load a snapshot by ID from localStorage.
* Returns the parsed snapshot object or null.
*/
function loadSnapshot(exportId) {
try {
const raw = localStorage.getItem(`snapshot_${exportId}`);
if (!raw) return null;
return JSON.parse(raw);
} catch {
return null;
}
}
/**
* Get snapshot ID from current URL query params.
* Returns the ID string or null.
*/
function getSnapshotIdFromUrl() {
try {
const params = new URLSearchParams(window.location.search);
return params.get("snapshot") || null;
} catch {
return null;
}
}
/**
* Delete a snapshot by ID.
*/
function deleteSnapshot(exportId) {
localStorage.removeItem(`snapshot_${exportId}`);
try {
const index = JSON.parse(localStorage.getItem('snapshotIndex') || '[]');
const filtered = index.filter(s => s.exportId !== exportId);
localStorage.setItem('snapshotIndex', JSON.stringify(filtered));
} catch {}
}
// Snapshot utilities
async function generateSnapshot() {
const payload = buildProgressExportPayload({ roleContext: "learner" });
const exportId = `snapshot_${Date.now()}_${Math.random().toString(16).slice(2)}`;
const encoder = new TextEncoder();
const data = encoder.encode(JSON.stringify(payload));
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const payloadHash = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
const snapshot = { payload, payloadHash, generatedAt: new Date().toISOString() };
localStorage.setItem(`snapshot_${exportId}`, JSON.stringify(snapshot));
const index = JSON.parse(localStorage.getItem('snapshotIndex') || '[]');
index.push({ exportId, generatedAt: snapshot.generatedAt, payloadHash });
localStorage.setItem('snapshotIndex', JSON.stringify(index));
return exportId;
}
function downloadSnapshotAsImage(exportId) {
const snapshotStr = localStorage.getItem(`snapshot_${exportId}`);
if (!snapshotStr) { alert('Snapshot not found'); return; }
const snapshot = JSON.parse(snapshotStr);
const iframe = createSnapshotFrame(snapshot.payload);
setTimeout(() => {
html2canvas(iframe.contentDocument.body).then(canvas => {
const link = document.createElement('a');
link.href = canvas.toDataURL('image/png');
link.download = `${exportId}.png`;
link.click();
iframe.remove();
});
}, 500);
}
function downloadSnapshotAsPDF(exportId) {
const snapshotStr = localStorage.getItem(`snapshot_${exportId}`);
if (!snapshotStr) { alert('Snapshot not found'); return; }
const snapshot = JSON.parse(snapshotStr);
const iframe = createSnapshotFrame(snapshot.payload);
setTimeout(() => {
html2canvas(iframe.contentDocument.body).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jspdf.jsPDF();
const imgProps = pdf.getImageProperties(imgData);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
pdf.save(`${exportId}.pdf`);
iframe.remove();
});
}, 500);
}
function listSnapshots() {
return JSON.parse(localStorage.getItem('snapshotIndex') || '[]');
}
function createSnapshotFrame(payload) {
const iframe = document.createElement('iframe');
iframe.style.position = 'fixed';
iframe.style.right = '0';
iframe.style.bottom = '0';
iframe.style.width = '0';
iframe.style.height = '0';
iframe.setAttribute('aria-hidden', 'true');
document.body.appendChild(iframe);
const doc = iframe.contentDocument;
doc.open();
doc.close();
const pre = doc.createElement('pre');
pre.textContent = JSON.stringify(payload, null, 2);
doc.body.appendChild(pre);
return iframe;
}
window.exportProgress = {
buildProgressExportPayload,
downloadJson,
downloadCsv,
buildCsvString,
generateSnapshot,
createShareableSnapshot,
loadSnapshot,
getSnapshotIdFromUrl,
listSnapshots,
deleteSnapshot,
downloadSnapshotAsImage,
downloadSnapshotAsPDF
};})();