Skip to main content

logicaffeine_web/
learn_state.rs

1//! Learn page state: where the learner stands on the roadmap, the question that closes a lesson,
2//! and the optional practice behind it.
3//!
4//! Everything here is pure (no Dioxus, no browser), so every rule is pinned by unit tests. The page
5//! renders these types and forwards clicks and keystrokes to them; it never keeps a second copy of
6//! the rules.
7//!
8//! - [`Journey`] walks the roadmap: which lesson is open and which are done. Any lesson can be
9//!   opened; finishing one and moving on opens the next in roadmap order.
10//! - [`LessonQuiz`] is a lesson's one question: answer it right, or try once and then ask to see the
11//!   answer, and the learner may move on.
12//! - [`PracticeSession`] walks a lesson's extra questions in order, bringing a missed one back after
13//!   [`RETRY_GAP`] others.
14
15use std::collections::{BTreeSet, HashSet, VecDeque};
16
17/// Where a learner stands on the roadmap: every lesson in order, the ones done, the one open.
18#[derive(Debug, Clone, PartialEq)]
19pub struct Journey {
20    order: Vec<String>,
21    done: BTreeSet<String>,
22    open: usize,
23}
24
25impl Journey {
26    /// `order` is every lesson id in roadmap order; `done` the lessons finished before (an id not on
27    /// the roadmap is dropped). `remembered` is the lesson open last time: it opens again while it is
28    /// on the roadmap, else the first lesson not done opens, else the first lesson.
29    pub fn new(
30        order: Vec<String>,
31        done: impl IntoIterator<Item = String>,
32        remembered: Option<&str>,
33    ) -> Self {
34        let on_roadmap: HashSet<&str> = order.iter().map(String::as_str).collect();
35        let done: BTreeSet<String> = done
36            .into_iter()
37            .filter(|id| on_roadmap.contains(id.as_str()))
38            .collect();
39        let open = remembered
40            .and_then(|id| order.iter().position(|o| o == id))
41            .or_else(|| order.iter().position(|o| !done.contains(o)))
42            .unwrap_or(0);
43        Self { order, done, open }
44    }
45
46    /// The open lesson, or `None` for an empty roadmap.
47    pub fn open(&self) -> Option<&str> {
48        self.order.get(self.open).map(String::as_str)
49    }
50
51    /// The lesson after the open one.
52    pub fn next(&self) -> Option<&str> {
53        self.order.get(self.open + 1).map(String::as_str)
54    }
55
56    pub fn len(&self) -> usize {
57        self.order.len()
58    }
59
60    pub fn is_empty(&self) -> bool {
61        self.order.is_empty()
62    }
63
64    pub fn done_count(&self) -> usize {
65        self.done.len()
66    }
67
68    pub fn is_done(&self, id: &str) -> bool {
69        self.done.contains(id)
70    }
71
72    /// Whether every lesson on a non-empty roadmap is done.
73    pub fn is_finished(&self) -> bool {
74        !self.order.is_empty() && self.done.len() == self.order.len()
75    }
76
77    /// The lessons done, in id order.
78    pub fn done_ids(&self) -> impl Iterator<Item = &str> + '_ {
79        self.done.iter().map(String::as_str)
80    }
81
82    /// Mark the open lesson done. It stays open.
83    pub fn finish(&mut self) {
84        if let Some(id) = self.order.get(self.open) {
85            self.done.insert(id.clone());
86        }
87    }
88
89    /// Open the next lesson in roadmap order. `false` at the end of the roadmap.
90    pub fn advance(&mut self) -> bool {
91        let moved = self.open + 1 < self.order.len();
92        if moved {
93            self.open += 1;
94        }
95        moved
96    }
97
98    /// Open `id`. `false` when it is not on the roadmap.
99    pub fn open_lesson(&mut self, id: &str) -> bool {
100        match self.order.iter().position(|o| o == id) {
101            Some(at) => {
102                self.open = at;
103                true
104            }
105            None => false,
106        }
107    }
108
109    /// Open the first of `ids` not done, or the first of them when all are done: how a link to a
110    /// module opens it. `false` when none of `ids` is on the roadmap.
111    pub fn open_first_unfinished(&mut self, ids: &[&str]) -> bool {
112        let on_roadmap: Vec<&str> = ids
113            .iter()
114            .copied()
115            .filter(|id| self.order.iter().any(|o| o == id))
116            .collect();
117        match on_roadmap
118            .iter()
119            .find(|id| !self.done.contains(**id))
120            .or(on_roadmap.first())
121        {
122            Some(id) => self.open_lesson(id),
123            None => false,
124        }
125    }
126}
127
128/// Where a lesson's question stands.
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
130pub enum QuizState {
131    /// Waiting for a right answer.
132    #[default]
133    Answering,
134    /// Answered right.
135    Correct,
136    /// The learner asked to see the answer after a try.
137    Shown,
138}
139
140/// A lesson's one question.
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
142pub struct LessonQuiz {
143    state: QuizState,
144    wrong: u32,
145}
146
147impl LessonQuiz {
148    pub fn state(&self) -> QuizState {
149        self.state
150    }
151
152    /// Wrong answers so far.
153    pub fn wrong_attempts(&self) -> u32 {
154        self.wrong
155    }
156
157    /// Grade an answer. Ignored once the question is settled.
158    pub fn answer(&mut self, correct: bool) {
159        if self.state != QuizState::Answering {
160            return;
161        }
162        if correct {
163            self.state = QuizState::Correct;
164        } else {
165            self.wrong += 1;
166        }
167    }
168
169    /// Whether the answer may be shown: after a wrong try, before the question is settled.
170    pub fn can_show_answer(&self) -> bool {
171        self.state == QuizState::Answering && self.wrong > 0
172    }
173
174    /// Show the answer. `false` when it may not be shown yet.
175    pub fn show_answer(&mut self) -> bool {
176        let allowed = self.can_show_answer();
177        if allowed {
178            self.state = QuizState::Shown;
179        }
180        allowed
181    }
182
183    /// Whether the question is answered or shown: it takes no more answers.
184    pub fn is_settled(&self) -> bool {
185        self.state != QuizState::Answering
186    }
187
188    /// Whether the learner may move on to the next lesson.
189    pub fn can_continue(&self) -> bool {
190        self.is_settled()
191    }
192}
193
194/// How many other questions come between a missed one and its retry.
195pub const RETRY_GAP: usize = 3;
196
197/// A walk through a lesson's practice questions.
198#[derive(Debug, Clone, PartialEq)]
199pub struct PracticeSession {
200    total: usize,
201    current: usize,
202    /// Where the in-order walk stands; a retry interrupts the walk without moving it.
203    cursor: usize,
204    served: usize,
205    retries: VecDeque<Retry>,
206    completed: HashSet<usize>,
207    revealed: HashSet<usize>,
208    solved_current: bool,
209}
210
211#[derive(Debug, Clone, Copy, PartialEq)]
212struct Retry {
213    index: usize,
214    due: usize,
215}
216
217impl PracticeSession {
218    /// A session over `total` questions. `completed` are questions answered right before: the walk
219    /// starts at the first one not in it.
220    pub fn new(total: usize, completed: impl IntoIterator<Item = usize>) -> Self {
221        let completed: HashSet<usize> = completed.into_iter().filter(|&i| i < total).collect();
222        let current = (0..total).find(|i| !completed.contains(i)).unwrap_or(0);
223        Self {
224            total,
225            current,
226            cursor: current,
227            served: 0,
228            retries: VecDeque::new(),
229            completed,
230            revealed: HashSet::new(),
231            solved_current: false,
232        }
233    }
234
235    /// The question on screen, or `None` when there are none.
236    pub fn current(&self) -> Option<usize> {
237        (self.total > 0).then_some(self.current)
238    }
239
240    pub fn total(&self) -> usize {
241        self.total
242    }
243
244    /// Questions answered right, in this session or an earlier one.
245    pub fn completed_count(&self) -> usize {
246        self.completed.len()
247    }
248
249    pub fn is_completed(&self, index: usize) -> bool {
250        self.completed.contains(&index)
251    }
252
253    /// Counts arrivals: every Next or Skip starts a new visit, even when it lands back on the same
254    /// question, so a view keyed by it always opens a question with a blank answer.
255    pub fn visit(&self) -> usize {
256        self.served
257    }
258
259    /// Whether the question on screen has been answered right since it came up.
260    pub fn solved_current(&self) -> bool {
261        self.solved_current
262    }
263
264    /// Whether the answer to the question on screen has been shown.
265    pub fn is_revealed(&self) -> bool {
266        self.revealed.contains(&self.current)
267    }
268
269    /// Missed questions waiting to come back, in the order they will.
270    pub fn pending_retries(&self) -> Vec<usize> {
271        self.retries.iter().map(|r| r.index).collect()
272    }
273
274    /// Grade the question on screen. A wrong answer to a question not yet completed queues it to come
275    /// back after [`RETRY_GAP`] others.
276    pub fn answer(&mut self, correct: bool) {
277        if self.total == 0 {
278            return;
279        }
280        let index = self.current;
281        if correct {
282            self.solved_current = true;
283            self.completed.insert(index);
284        } else if !self.completed.contains(&index) && !self.retries.iter().any(|r| r.index == index)
285        {
286            self.retries.push_back(Retry {
287                index,
288                due: self.served + RETRY_GAP + 1,
289            });
290        }
291    }
292
293    /// Show the answer to the question on screen.
294    pub fn reveal_answer(&mut self) {
295        if self.total > 0 {
296            self.revealed.insert(self.current);
297        }
298    }
299
300    /// Move on (Next or Skip). A missed question whose retry is due comes first; otherwise the next
301    /// question not yet completed, wrapping around; once everything is completed, the walk simply
302    /// continues in order.
303    pub fn advance(&mut self) {
304        if self.total == 0 {
305            return;
306        }
307        self.served += 1;
308        self.solved_current = false;
309
310        let mut still_waiting = VecDeque::new();
311        let mut next_retry = None;
312        while let Some(retry) = self.retries.pop_front() {
313            if self.completed.contains(&retry.index) {
314                continue;
315            }
316            if next_retry.is_none() && retry.due <= self.served && retry.index != self.current {
317                next_retry = Some(retry.index);
318            } else {
319                still_waiting.push_back(retry);
320            }
321        }
322        self.retries = still_waiting;
323
324        self.current = match next_retry {
325            Some(index) => index,
326            None => {
327                self.cursor = self.next_in_order();
328                self.cursor
329            }
330        };
331    }
332
333    fn next_in_order(&self) -> usize {
334        let ahead = || (1..=self.total).map(|step| (self.cursor + step) % self.total);
335        ahead()
336            .find(|i| !self.completed.contains(i) && *i != self.current)
337            .or_else(|| ahead().find(|i| *i != self.current))
338            .unwrap_or(self.current)
339    }
340}
341
342#[cfg(test)]
343#[path = "../../../crates/logicaffeine_tests/unit/logicaffeine_web/learn_state/tests.rs"]
344mod tests;