1use include_dir::{include_dir, Dir};
2use serde::Deserialize;
3use std::cmp::Ordering;
4use std::collections::HashMap;
5use std::sync::LazyLock;
6
7static CURRICULUM_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/assets/curriculum");
10
11static SHARED: LazyLock<ContentEngine> = LazyLock::new(ContentEngine::new);
13
14#[derive(Debug, Clone, Deserialize)]
15pub struct EraMeta {
16 pub id: String,
17 pub title: String,
18 pub description: String,
19 pub order: u32,
20}
21
22#[derive(Debug, Clone, Deserialize)]
23pub struct ModuleMeta {
24 pub id: String,
25 pub title: String,
26 pub pedagogy: String,
27 pub order: u32,
28 pub summary: String,
30}
31
32#[derive(Debug, Clone, Deserialize)]
33pub struct ExerciseConfig {
34 pub id: String,
35 #[serde(rename = "type")]
36 pub exercise_type: ExerciseType,
37 pub difficulty: u32,
38 pub prompt: String,
39 #[serde(default)]
40 pub template: Option<String>,
41 #[serde(default)]
42 pub constraints: HashMap<String, Vec<String>>,
43 #[serde(default)]
44 pub hint: Option<String>,
45 #[serde(default)]
46 pub explanation: Option<String>,
47 #[serde(default)]
48 pub options: Option<Vec<String>>,
49 #[serde(default)]
50 pub correct: Option<usize>,
51 #[serde(default)]
53 pub section: Option<String>,
54}
55
56#[derive(Debug, Clone, Deserialize, PartialEq)]
57#[serde(rename_all = "snake_case")]
58pub enum ExerciseType {
59 Translation,
60 MultipleChoice,
61 Ambiguity,
62}
63
64#[derive(Debug, Clone, Deserialize)]
66pub struct SymbolDef {
67 pub symbol: String,
68 pub name: String,
69 pub meaning: String,
70 #[serde(default)]
71 pub example: Option<String>,
72}
73
74#[derive(Debug, Clone, Deserialize)]
77#[serde(tag = "type", rename_all = "snake_case")]
78pub enum ContentBlock {
79 Paragraph {
80 text: String,
81 },
82 Definition {
83 term: String,
84 definition: String,
85 },
86 Symbols {
88 title: String,
89 symbols: Vec<SymbolDef>,
90 },
91}
92
93#[derive(Debug, Clone, Deserialize)]
95pub struct Section {
96 pub id: String,
97 pub title: String,
98 pub order: u32,
99 #[serde(default)]
101 pub content: Vec<ContentBlock>,
102 #[serde(default)]
104 pub examples: Vec<LessonExample>,
105 #[serde(default)]
107 pub question: Option<LessonQuestion>,
108}
109
110#[derive(Debug, Clone, Deserialize)]
112#[serde(tag = "type", rename_all = "snake_case")]
113pub enum LessonExample {
114 Formula {
116 sentence: String,
117 formula: String,
118 #[serde(default)]
119 note: Option<String>,
120 },
121 Worked {
123 title: String,
124 lines: Vec<String>,
125 #[serde(default)]
126 conclusion: Option<String>,
127 #[serde(default)]
128 note: Option<String>,
129 },
130}
131
132#[derive(Debug, Clone, Deserialize)]
134#[serde(tag = "type", rename_all = "snake_case")]
135pub enum LessonQuestion {
136 Translate {
138 sentence: String,
139 answer: String,
140 hint: String,
141 explanation: String,
142 },
143 Choice {
145 prompt: String,
146 options: Vec<String>,
147 correct: usize,
148 hint: String,
149 explanation: String,
150 },
151}
152
153#[derive(Debug, Clone)]
154pub struct Module {
155 pub meta: ModuleMeta,
156 pub exercises: Vec<ExerciseConfig>,
157 pub sections: Vec<Section>,
158}
159
160#[derive(Debug, Clone)]
161pub struct Era {
162 pub meta: EraMeta,
163 pub modules: Vec<Module>,
164}
165
166#[derive(Debug, Clone)]
167pub struct Curriculum {
168 pub eras: Vec<Era>,
169}
170
171pub struct ContentEngine {
172 pub curriculum: Curriculum,
173}
174
175#[derive(Debug, Clone, Copy)]
177pub struct Lesson<'a> {
178 pub era: &'a Era,
179 pub module: &'a Module,
180 pub section: &'a Section,
181}
182
183impl ContentEngine {
184 pub fn new() -> Self {
185 let (curriculum, _) = Self::load_curriculum();
186 Self { curriculum }
187 }
188
189 pub fn shared() -> &'static ContentEngine {
192 &SHARED
193 }
194
195 pub fn load_issues() -> Vec<String> {
198 Self::load_curriculum().1
199 }
200
201 fn load_curriculum() -> (Curriculum, Vec<String>) {
202 Self::load_from(&CURRICULUM_DIR)
203 }
204
205 fn load_from(root: &Dir) -> (Curriculum, Vec<String>) {
206 let mut eras = Vec::new();
207 let mut issues = Vec::new();
208
209 for file in root.files() {
210 issues.push(format!(
211 "{}: stray file at the curriculum root",
212 file.path().display()
213 ));
214 }
215 for era_entry in root.dirs() {
216 if let Some(era) = Self::load_era(era_entry, &mut issues) {
217 eras.push(era);
218 }
219 }
220
221 eras.sort_by_key(|e| e.meta.order);
222 (Curriculum { eras }, issues)
223 }
224
225 fn load_era(era_dir: &Dir, issues: &mut Vec<String>) -> Option<Era> {
226 let meta_path = era_dir.path().join("meta.json");
227 let meta: EraMeta = parse_file(era_dir, &meta_path, issues)?;
228
229 for file in era_dir.files() {
230 if file.path() != meta_path {
231 issues.push(format!(
232 "{}: stray file in an era directory",
233 file.path().display()
234 ));
235 }
236 }
237
238 let mut modules = Vec::new();
239 for module_entry in era_dir.dirs() {
240 if let Some(module) = Self::load_module(module_entry, issues) {
241 modules.push(module);
242 }
243 }
244
245 modules.sort_by_key(|m| m.meta.order);
246 Some(Era { meta, modules })
247 }
248
249 fn load_module(module_dir: &Dir, issues: &mut Vec<String>) -> Option<Module> {
250 let meta_path = module_dir.path().join("meta.json");
251 let meta: ModuleMeta = parse_file(module_dir, &meta_path, issues)?;
252
253 let mut exercises = Vec::new();
254 let mut sections = Vec::new();
255
256 for file in module_dir.files() {
257 let path = file.path();
258 if path == meta_path {
259 continue;
260 }
261 let name = path
262 .file_name()
263 .map(|n| n.to_string_lossy())
264 .unwrap_or_default();
265 if !name.ends_with(".json") {
266 issues.push(format!(
267 "{}: stray file in a module directory",
268 path.display()
269 ));
270 } else if name.starts_with("ex_") {
271 exercises.extend(parse_file::<ExerciseConfig>(module_dir, path, issues));
272 } else if name.starts_with("sec_") {
273 sections.extend(parse_file::<Section>(module_dir, path, issues));
274 } else {
275 issues.push(format!(
276 "{}: not loaded — module files are meta.json, ex_*.json or sec_*.json",
277 path.display()
278 ));
279 }
280 }
281 for dir in module_dir.dirs() {
282 issues.push(format!(
283 "{}: stray directory in a module directory",
284 dir.path().display()
285 ));
286 }
287
288 exercises.sort_by(|a, b| natural_cmp(&a.id, &b.id));
289 sections.sort_by_key(|s| s.order);
290 Some(Module {
291 meta,
292 exercises,
293 sections,
294 })
295 }
296
297 pub fn get_era(&self, era_id: &str) -> Option<&Era> {
298 self.curriculum.eras.iter().find(|e| e.meta.id == era_id)
299 }
300
301 pub fn get_module(&self, era_id: &str, module_id: &str) -> Option<&Module> {
302 self.get_era(era_id)?
303 .modules
304 .iter()
305 .find(|m| m.meta.id == module_id)
306 }
307
308 pub fn get_exercise(
309 &self,
310 era_id: &str,
311 module_id: &str,
312 exercise_id: &str,
313 ) -> Option<&ExerciseConfig> {
314 self.get_module(era_id, module_id)?
315 .exercises
316 .iter()
317 .find(|e| e.id == exercise_id)
318 }
319
320 pub fn eras(&self) -> &[Era] {
321 &self.curriculum.eras
322 }
323
324 pub fn era_count(&self) -> usize {
325 self.curriculum.eras.len()
326 }
327
328 pub fn lessons(&self) -> Vec<Lesson<'_>> {
330 self.curriculum
331 .eras
332 .iter()
333 .flat_map(|era| era.modules.iter().map(move |module| (era, module)))
334 .flat_map(|(era, module)| {
335 module.sections.iter().map(move |section| Lesson {
336 era,
337 module,
338 section,
339 })
340 })
341 .collect()
342 }
343
344 pub fn lesson(&self, id: &str) -> Option<Lesson<'_>> {
346 self.lessons()
347 .into_iter()
348 .find(|lesson| lesson.section.id == id)
349 }
350
351 pub fn exercise_count(&self, era_id: &str, module_id: &str) -> usize {
352 self.get_module(era_id, module_id)
353 .map(|m| m.exercises.len())
354 .unwrap_or(0)
355 }
356}
357
358impl Default for ContentEngine {
359 fn default() -> Self {
360 Self::new()
361 }
362}
363
364fn parse_file<T: serde::de::DeserializeOwned>(
365 dir: &Dir,
366 path: &std::path::Path,
367 issues: &mut Vec<String>,
368) -> Option<T> {
369 let Some(file) = dir.get_file(path) else {
370 issues.push(format!("{}: missing", path.display()));
371 return None;
372 };
373 let Some(text) = file.contents_utf8() else {
374 issues.push(format!("{}: not UTF-8", path.display()));
375 return None;
376 };
377 serde_json::from_str(text)
378 .map_err(|e| issues.push(format!("{}: {e}", path.display())))
379 .ok()
380}
381
382pub fn natural_cmp(a: &str, b: &str) -> Ordering {
387 let (mut x, mut y) = (a.as_bytes(), b.as_bytes());
388 loop {
389 match (x.first(), y.first()) {
390 (None, None) => return a.cmp(b),
391 (None, Some(_)) => return Ordering::Less,
392 (Some(_), None) => return Ordering::Greater,
393 (Some(p), Some(q)) if p.is_ascii_digit() && q.is_ascii_digit() => {
394 let (dx, rx) = split_digits(x);
395 let (dy, ry) = split_digits(y);
396 let (tx, ty) = (trim_zeros(dx), trim_zeros(dy));
397 let by_value = tx.len().cmp(&ty.len()).then_with(|| tx.cmp(ty));
398 if by_value != Ordering::Equal {
399 return by_value;
400 }
401 x = rx;
402 y = ry;
403 }
404 (Some(p), Some(q)) => {
405 let by_text = p.to_ascii_lowercase().cmp(&q.to_ascii_lowercase());
406 if by_text != Ordering::Equal {
407 return by_text;
408 }
409 x = &x[1..];
410 y = &y[1..];
411 }
412 }
413 }
414}
415
416fn split_digits(s: &[u8]) -> (&[u8], &[u8]) {
417 let n = s.iter().take_while(|c| c.is_ascii_digit()).count();
418 s.split_at(n)
419}
420
421fn trim_zeros(digits: &[u8]) -> &[u8] {
422 let n = digits.iter().take_while(|&&c| c == b'0').count();
423 &digits[n..]
424}
425
426#[cfg(test)]
427#[path = "../../../crates/logicaffeine_tests/unit/logicaffeine_web/content/tests.rs"]
428mod tests;