feat: support readings and lecture rendering

This commit is contained in:
alexm committed 2026-08-08 16:24:50 -04:00
1 parent 468af3a815
commit f475c630e0
10 files changed
+1535 -11

No files matched your search

+414
View File
@@ -0,0 +1,414 @@
// SPDX-License-Identifier: Prosperity-3.0.0
// Copyright Scientific Computing Studio
// Source: https://git.scient.ing/education/coursebank
//! Rendering a lecture's objectives and readings as Markdown.
//!
//! The course file is the source of truth for what a lecture assigns and why, so
//! the reading list on the course website is generated rather than kept in step by
//! hand. Two copies of the same prose drift within a term; one copy and a build
//! step do not.
//!
//! [`Style::Quarto`] reproduces the definition-list shape a Quarto page wants,
//! with `_(LO 4, 7)_` numbering resolved from [`CourseFile::lecture_objectives`].
//! Those numbers are positional and so cannot be authored: inserting an objective
//! renumbers everything after it. They are computed here and never stored.
//!
//! What this module does not do is invent prose. Everything printed comes from
//! `summary`, `focus`, and `skip` on the reading, in that order, and a reading with
//! none of the three renders as a bare citation.
use crate::course::{CourseFile, Reading, ReadingRole, Reference};
use crate::error::{Error, Result};
use crate::taxonomy::Level;
/// Which flavour of Markdown to emit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Style {
/// Pandoc definition lists with `<br>` before the objective line, which is
/// what a Quarto lecture page uses.
#[default]
Quarto,
/// Plain Markdown bullets, for a report or a README.
Plain,
}
/// Renders the objectives for one lecture, grouped by level.
///
/// The numbering here and the `_(LO 4, 7)_` lists in [`readings_markdown`] come
/// from the same call to [`CourseFile::lecture_objectives`], so they cannot
/// disagree. Generating one half of the page and hand-writing the other is how you
/// get a note pointing at LO 8 when LO 8 has become LO 9.
///
/// # Arguments
///
/// * `course` - the loaded course file.
/// * `lecture` - the lecture id.
/// * `style` - which flavour to emit.
///
/// # Returns
///
/// The Markdown, ending in a newline. Objectives with no `level_ceiling` are
/// grouped last under no heading.
///
/// # Errors
///
/// Returns [`Error::Unresolved`] when the lecture id is not registered.
pub fn objectives_markdown(course: &CourseFile, lecture: &str, style: Style) -> Result<String> {
course.lecture(lecture, "lecture page")?;
let ids = course.lecture_objectives(lecture);
let mut out = String::from("## Learning objectives\n\n");
out.push_str("After this lecture, you should be able to do the following.\n\n");
// Levels in taxonomy order, then whatever declares no ceiling.
let mut groups: Vec<(Option<Level>, Vec<&str>)> =
Level::ALL.iter().map(|l| (Some(*l), Vec::new())).collect();
groups.push((None, Vec::new()));
for id in &ids {
let ceiling = course.learning_objectives[*id].level_ceiling;
if let Some(slot) = groups.iter_mut().find(|(level, _)| *level == ceiling) {
slot.1.push(id);
}
}
for (level, members) in &groups {
if members.is_empty() {
continue;
}
if let Some(level) = level {
out.push_str(&format!("### {}\n\n", level.name()));
}
for id in members {
let text = course.objective_text(id);
out.push_str(&match style {
Style::Quarto => format!("(@) {text}\n"),
Style::Plain => format!("1. {text}\n"),
});
}
out.push('\n');
}
Ok(out)
}
/// Renders the readings for one lecture.
///
/// # Arguments
///
/// * `course` - the loaded course file.
/// * `lecture` - the lecture id, such as `L1.1`.
/// * `style` - which flavour to emit.
///
/// # Returns
///
/// The Markdown, ending in a newline. Supplemental readings follow the assigned
/// ones under their own subheading, and are omitted entirely when there are none.
///
/// # Errors
///
/// Returns [`Error::Unresolved`] when the lecture id or a cited reference is not
/// registered.
pub fn readings_markdown(course: &CourseFile, lecture: &str, style: Style) -> Result<String> {
let lec = course.lecture(lecture, "lecture page")?;
// Positional numbers for this page, so `{lo-id}` in a note and the trailing
// `_(LO ...)_` agree with the objective list printed above them.
let order = course.lecture_objectives(lecture);
let number = |id: &str| order.iter().position(|o| *o == id).map(|i| i + 1);
let mut out = String::from("## Readings\n\n");
for role in [ReadingRole::Assigned, ReadingRole::Supplemental] {
let group: Vec<&Reading> = lec.readings.iter().filter(|r| r.role == role).collect();
if group.is_empty() {
continue;
}
if role == ReadingRole::Supplemental {
out.push_str("### Supplemental\n\n");
}
for reading in group {
out.push_str(&entry(course, reading, style, &number)?);
}
}
Ok(out)
}
/// Renders one reading.
///
/// # Arguments
///
/// * `course` - the course, for resolving references and placeholders.
/// * `reading` - the reading.
/// * `style` - which flavour to emit.
/// * `number` - the position of an objective on this page, if it has one.
///
/// # Returns
///
/// The entry, followed by a blank line.
///
/// # Errors
///
/// Returns [`Error::Unresolved`] when the cited reference is not registered.
fn entry(
course: &CourseFile,
reading: &Reading,
style: Style,
number: &impl Fn(&str) -> Option<usize>,
) -> Result<String> {
// A reading carried over from the old string form has nothing to resolve.
if let (None, Some(text)) = (&reading.reference, &reading.text) {
return Ok(match style {
Style::Quarto => format!("{text}\n\n"),
Style::Plain => format!("- {text}\n"),
});
}
let key = reading
.reference
.as_deref()
.ok_or_else(|| Error::other("reading has neither a reference nor text"))?;
let reference = course.reference(key, "lecture page")?;
let mut out = String::new();
out.push_str(&heading(reading, key, reference, style));
// The three prose fields in the order a reader wants them: what it is, what to
// take from it, what to leave.
let body: Vec<String> = [&reading.summary, &reading.focus, &reading.skip]
.into_iter()
.flatten()
.map(|prose| {
course.expand_objective_refs(prose, |id| match number(id) {
Some(n) => format!("LO {n}"),
None => course.objective_text(id),
})
})
.collect();
match style {
Style::Quarto => {
if !body.is_empty() {
out.push_str(&format!(": {}\n", body.join("\n")));
}
let mut numbers: Vec<usize> = reading
.objectives
.iter()
.filter_map(|o| number(o))
.collect();
numbers.sort_unstable();
if !numbers.is_empty() {
let list: Vec<String> = numbers.iter().map(|n| n.to_string()).collect();
out.push_str(&format!("<br>\n_(LO {})_\n", list.join(", ")));
}
out.push('\n');
}
Style::Plain => {
if !body.is_empty() {
out.push_str(&format!(" {}\n", body.join(" ")));
}
}
}
Ok(out)
}
/// The citation line that opens an entry.
///
/// # Arguments
///
/// * `reading` - the reading.
/// * `key` - its citation key.
/// * `reference` - the cited work.
/// * `style` - which flavour to emit.
///
/// # Returns
///
/// A linked citation when the location has a URL, and a plain one when it does not.
fn heading(reading: &Reading, key: &str, reference: &Reference, style: Style) -> String {
let label = reference.label.as_deref().unwrap_or(key);
let locator = reading.locator.as_deref().unwrap_or("");
let linked = match reading.resolve_url(reference) {
Some(url) if !locator.is_empty() => format!("[{locator}]({url})"),
Some(url) => format!("[{}]({url})", reference.title),
None if !locator.is_empty() => locator.to_string(),
None => reference.title.clone(),
};
match style {
Style::Quarto => format!("`{label}` {linked}\n"),
Style::Plain => format!("- **{label}** {linked}\n"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::course::{Lecture, Objective, ReferenceRole};
/// A course with one lecture, two objectives, and one reference.
fn course() -> CourseFile {
let mut c = CourseFile::skeleton("BIOSC 1000", "Biochemistry", "2026f");
c.lectures.clear();
c.learning_objectives.clear();
c.references.insert(
"kuriyan2013molecules".into(),
Reference {
label: Some("KKW".into()),
role: ReferenceRole::Required,
title: "The molecules of life".into(),
base_url: Some("https://example.org/kkw/".into()),
..Reference::default()
},
);
for (id, order) in [("lo-second", 2), ("lo-first", 1)] {
c.learning_objectives.insert(
id.into(),
Objective {
text: format!("objective {id}"),
lectures: vec!["L1.1".into()],
order: Some(order),
..objective_defaults()
},
);
}
c.lectures.insert(
"L1.1".into(),
Lecture {
title: "Enthalpy".into(),
date: None,
unit: None,
slides_url: None,
readings: vec![
Reading {
reference: Some("kuriyan2013molecules".into()),
locator: Some("§6.1".into()),
path: Some("6/A/#1".into()),
objectives: vec!["lo-second".into(), "lo-first".into()],
summary: Some("What a system is.".into()),
focus: Some("A worked instance of {lo-first}.".into()),
..Reading::default()
},
Reading {
reference: Some("kuriyan2013molecules".into()),
locator: Some("§1.9".into()),
path: Some("1/B/#9".into()),
role: ReadingRole::Supplemental,
objectives: vec!["lo-second".into()],
summary: Some("Background.".into()),
..Reading::default()
},
],
},
);
c
}
/// The non-defaulted half of an objective, so the fixtures stay short.
fn objective_defaults() -> Objective {
Objective {
text: String::new(),
unit: None,
lectures: Vec::new(),
order: None,
level_ceiling: None,
prerequisites: Vec::new(),
tags: Vec::new(),
assessed: true,
}
}
#[test]
fn the_quarto_form_matches_the_page_it_replaces() {
let md = readings_markdown(&course(), "L1.1", Style::Quarto).expect("renders");
let expected = "\
## Readings
`KKW` [§6.1](https://example.org/kkw/6/A/#1)
: What a system is.
A worked instance of LO 1.
<br>
_(LO 1, 2)_
### Supplemental
`KKW` [§1.9](https://example.org/kkw/1/B/#9)
: Background.
<br>
_(LO 2)_
";
assert_eq!(md, expected);
}
#[test]
fn objective_numbers_follow_teaching_order_not_id_order() {
// `lo-second` sorts first alphabetically and second by `order`.
let md = readings_markdown(&course(), "L1.1", Style::Quarto).expect("renders");
assert!(md.contains("_(LO 1, 2)_"));
assert!(md.contains("A worked instance of LO 1."));
}
#[test]
fn objectives_group_by_level_in_taxonomy_order() {
let mut c = course();
c.learning_objectives
.get_mut("lo-first")
.expect("fixture")
.level_ceiling = Some(Level::Remember);
c.learning_objectives
.get_mut("lo-second")
.expect("fixture")
.level_ceiling = Some(Level::Apply);
let md = objectives_markdown(&c, "L1.1", Style::Quarto).expect("renders");
let expected = "\
## Learning objectives
After this lecture, you should be able to do the following.
### Remember
(@) objective lo-first
### Apply
(@) objective lo-second
";
assert_eq!(md, expected);
}
#[test]
fn an_objective_with_no_level_still_appears() {
// Ungrouped, at the end, rather than silently dropped.
let md = objectives_markdown(&course(), "L1.1", Style::Quarto).expect("renders");
assert!(md.contains("(@) objective lo-first"));
assert!(md.contains("(@) objective lo-second"));
assert!(!md.contains("###"));
}
#[test]
fn a_supplemental_heading_appears_only_when_something_is_under_it() {
let mut c = course();
c.lectures.get_mut("L1.1").expect("lecture").readings.pop();
let md = readings_markdown(&c, "L1.1", Style::Quarto).expect("renders");
assert!(!md.contains("Supplemental"));
}
#[test]
fn a_legacy_string_reading_still_renders() {
let mut c = course();
let readings = &mut c.lectures.get_mut("L1.1").expect("lecture").readings;
readings.clear();
readings.push(Reading {
text: Some("KKW §6.1: system and surroundings. https://example.org".into()),
..Reading::default()
});
let md = readings_markdown(&c, "L1.1", Style::Quarto).expect("renders");
assert!(md.contains("system and surroundings"));
}
#[test]
fn an_unknown_reference_is_an_error_rather_than_a_blank() {
let mut c = course();
c.references.clear();
let err = readings_markdown(&c, "L1.1", Style::Quarto);
assert!(err.is_err());
}
}