logicaffeine_web/
progress.rs1use serde::{Deserialize, Serialize};
9use std::collections::{BTreeSet, HashMap};
10
11#[derive(Debug, Clone, Serialize, Deserialize, Default)]
12#[serde(default)]
13pub struct UserProgress {
14 pub exercises: HashMap<String, ExerciseProgress>,
16 pub lessons: BTreeSet<String>,
18 pub open_lesson: Option<String>,
20}
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct ExerciseProgress {
24 pub exercise_id: String,
25 pub attempts: u32,
26 pub correct_count: u32,
27 pub last_attempt: Option<String>,
28 pub srs: SrsData,
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct SrsData {
33 pub ease_factor: f64,
34 pub interval: u32,
35 pub repetitions: u32,
36 pub next_review: Option<String>,
37}
38
39impl Default for SrsData {
40 fn default() -> Self {
41 Self {
42 ease_factor: 2.5,
43 interval: 1,
44 repetitions: 0,
45 next_review: None,
46 }
47 }
48}
49
50impl UserProgress {
51 pub fn new() -> Self {
52 Self::default()
53 }
54
55 pub fn load() -> Self {
56 #[cfg(target_arch = "wasm32")]
57 {
58 crate::storage::load_raw()
59 .and_then(|json| serde_json::from_str(&json).ok())
60 .unwrap_or_default()
61 }
62 #[cfg(not(target_arch = "wasm32"))]
63 {
64 Self::new()
65 }
66 }
67
68 pub fn save(&self) {
69 #[cfg(target_arch = "wasm32")]
70 {
71 if let Ok(json) = serde_json::to_string(self) {
72 crate::storage::save_raw(&json);
73 }
74 }
75 }
76
77 pub fn record_attempt(&mut self, exercise_id: &str, correct: bool) {
78 let entry = self
79 .exercises
80 .entry(exercise_id.to_string())
81 .or_insert_with(|| ExerciseProgress {
82 exercise_id: exercise_id.to_string(),
83 attempts: 0,
84 correct_count: 0,
85 last_attempt: None,
86 srs: SrsData::default(),
87 });
88
89 entry.attempts += 1;
90 if correct {
91 entry.correct_count += 1;
92 }
93
94 self.save();
95 }
96
97 pub fn get_exercise_progress(&self, exercise_id: &str) -> Option<&ExerciseProgress> {
98 self.exercises.get(exercise_id)
99 }
100
101 pub fn finish_lesson(&mut self, lesson_id: &str) {
103 self.lessons.insert(lesson_id.to_string());
104 }
105
106 pub fn is_lesson_done(&self, lesson_id: &str) -> bool {
107 self.lessons.contains(lesson_id)
108 }
109}
110
111#[cfg(test)]
112#[path = "../../../crates/logicaffeine_tests/unit/logicaffeine_web/progress/tests.rs"]
113mod tests;