feat: support readings and lecture rendering
This commit is contained in:
10 files changed
+1535
-11
No files matched your search
+766
-5
@@ -16,9 +16,12 @@
|
||||
//! belongs to the course and the administration, never to the item.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde::de::{self, MapAccess, Visitor};
|
||||
use serde::ser::SerializeMap;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
use crate::date::Date;
|
||||
use crate::error::{Error, Result};
|
||||
@@ -61,6 +64,12 @@ pub struct CourseFile {
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub learning_objectives: BTreeMap<String, Objective>,
|
||||
|
||||
/// Works the course cites, keyed by citation key such as
|
||||
/// `kuriyan2013molecules`. Readings point in here rather than restating a
|
||||
/// citation, so a reference is written once and a changed edition is one edit.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub references: BTreeMap<String, Reference>,
|
||||
|
||||
/// Shared stimuli for case-based testlets, keyed by id.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub stimuli: BTreeMap<String, Stimulus>,
|
||||
@@ -172,9 +181,318 @@ pub struct Lecture {
|
||||
/// Where the slides live, for study guidance in student reports.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub slides_url: Option<String>,
|
||||
/// Assigned readings for the session.
|
||||
/// Assigned readings for the session, in the order you assign them.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub readings: Vec<String>,
|
||||
pub readings: Vec<Reading>,
|
||||
}
|
||||
|
||||
/// A work the course cites: a textbook, an article, a dataset, a recording.
|
||||
///
|
||||
/// Keyed by citation key, so this registry is a bibliography rather than a second
|
||||
/// naming scheme. The field names follow BibTeX where BibTeX has one, which makes
|
||||
/// import and export mechanical.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Reference {
|
||||
/// The short form a reading list shows, such as `KKW`. Unique across the
|
||||
/// registry, because reports print it in place of the key.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub label: Option<String>,
|
||||
/// What kind of work this is, which decides how a citation renders.
|
||||
#[serde(default)]
|
||||
pub kind: ReferenceKind,
|
||||
/// Whether the course requires it or lists it as background.
|
||||
#[serde(default)]
|
||||
pub role: ReferenceRole,
|
||||
/// Full title.
|
||||
pub title: String,
|
||||
/// Authors as `Family, Given`, in the order printed on the work.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub authors: Vec<String>,
|
||||
/// Year of publication.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub year: Option<u32>,
|
||||
/// Edition as printed: `7th`, `Revised`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub edition: Option<String>,
|
||||
/// Publisher, for a book.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub publisher: Option<String>,
|
||||
/// The journal, edited volume, or series this sits inside.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub container: Option<String>,
|
||||
/// Volume within the container.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub volume: Option<String>,
|
||||
/// Issue within the volume.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub issue: Option<String>,
|
||||
/// Page range of the work as a whole, not of any one reading.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub pages: Option<String>,
|
||||
/// DOI, bare: `10.1038/nature12373`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub doi: Option<String>,
|
||||
/// ISBN, for a book.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub isbn: Option<String>,
|
||||
/// Canonical URL for the work as a whole.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub url: Option<String>,
|
||||
/// Prefix a reading's `path` is appended to. Having this means the citation
|
||||
/// key appears once rather than once per reading.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub base_url: Option<String>,
|
||||
/// Anything students need to know about getting hold of it: reserve shelf,
|
||||
/// license, paywall.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
/// The kind of work, chosen to map onto BibTeX entry types.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum ReferenceKind {
|
||||
/// A whole book.
|
||||
#[default]
|
||||
Book,
|
||||
/// A chapter in an edited volume.
|
||||
Chapter,
|
||||
/// A journal article.
|
||||
Article,
|
||||
/// A preprint, which is an article without a container.
|
||||
Preprint,
|
||||
/// A thesis or dissertation.
|
||||
Thesis,
|
||||
/// A page or resource that exists only online.
|
||||
Website,
|
||||
/// A program or library.
|
||||
Software,
|
||||
/// A published dataset.
|
||||
Dataset,
|
||||
/// A recording.
|
||||
Video,
|
||||
/// Anything else.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// Whether the course requires a work or offers it as background.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum ReferenceRole {
|
||||
/// A course text. Assigned readings come from it.
|
||||
Required,
|
||||
/// Listed so students know it exists. Never assigned.
|
||||
#[default]
|
||||
Supplemental,
|
||||
}
|
||||
|
||||
/// One assigned location inside a [`Reference`], and what it is assigned for.
|
||||
///
|
||||
/// The prose splits three ways because each part answers a different question and
|
||||
/// each has a different consumer. `summary` says what the section contains, `focus`
|
||||
/// says what to take from it, and `skip` says what to ignore. A student report
|
||||
/// quotes `focus` at somebody who missed the objective; a lecture page prints all
|
||||
/// three.
|
||||
///
|
||||
/// A reading written as a bare string, which is what this field held before the
|
||||
/// schema existed, still parses: the whole string lands in `text`, and serializing
|
||||
/// writes it back out as a string rather than a mapping.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Reading {
|
||||
/// Citation key into [`CourseFile::references`].
|
||||
pub reference: Option<String>,
|
||||
/// Where inside the work: `§6.1`, `pp. 212-219`, `ch. 3`, `fig. 4`.
|
||||
pub locator: Option<String>,
|
||||
/// Appended to the reference's `base_url` to reach this location.
|
||||
pub path: Option<String>,
|
||||
/// A full URL, for a location that is not under the reference's `base_url`.
|
||||
pub url: Option<String>,
|
||||
/// Whether it is assigned or offered alongside.
|
||||
pub role: ReadingRole,
|
||||
/// The objectives this reading serves.
|
||||
pub objectives: Vec<String>,
|
||||
/// What the section contains.
|
||||
pub summary: Option<String>,
|
||||
/// What to take from it, which is the sentence a study suggestion quotes.
|
||||
pub focus: Option<String>,
|
||||
/// What to gloss, and why it is out of scope.
|
||||
pub skip: Option<String>,
|
||||
/// A reading written as a bare string before this schema existed, held
|
||||
/// unparsed.
|
||||
pub text: Option<String>,
|
||||
}
|
||||
|
||||
/// Whether a reading is assigned or offered alongside.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum ReadingRole {
|
||||
/// Assigned, and therefore fair to assess.
|
||||
#[default]
|
||||
Assigned,
|
||||
/// Offered as background. Not separately assessed.
|
||||
Supplemental,
|
||||
}
|
||||
|
||||
impl Reading {
|
||||
/// The URL for this location.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `reference` - the work this reading is inside.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `url` when given, otherwise the reference's `base_url` joined with `path`,
|
||||
/// otherwise `None`.
|
||||
pub fn resolve_url(&self, reference: &Reference) -> Option<String> {
|
||||
if let Some(url) = &self.url {
|
||||
return Some(url.clone());
|
||||
}
|
||||
let path = self.path.as_deref()?;
|
||||
let base = reference.base_url.as_deref()?;
|
||||
Some(match (base.ends_with('/'), path.starts_with('/')) {
|
||||
(true, true) => format!("{base}{}", &path[1..]),
|
||||
(false, false) => format!("{base}/{path}"),
|
||||
_ => format!("{base}{path}"),
|
||||
})
|
||||
}
|
||||
|
||||
/// A short citation for a report: `KKW §6.1`.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `key` - the citation key, used when the reference declares no label.
|
||||
/// * `reference` - the work, for its label.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The label and locator, or the unparsed `text` for a legacy reading.
|
||||
pub fn cite(&self, key: &str, reference: &Reference) -> String {
|
||||
if let Some(text) = &self.text {
|
||||
return text.clone();
|
||||
}
|
||||
let label = reference.label.as_deref().unwrap_or(key);
|
||||
match &self.locator {
|
||||
Some(locator) => format!("{label} {locator}"),
|
||||
None => label.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a reading as a mapping, or as a bare string when that is all it holds.
|
||||
///
|
||||
/// The string case keeps a course file that predates this schema byte-identical
|
||||
/// through a load-and-save cycle, so migrating is something you choose rather than
|
||||
/// something the tool does to your file the first time it writes it.
|
||||
impl Serialize for Reading {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
|
||||
if let Some(text) = &self.text {
|
||||
if self.reference.is_none() && self.locator.is_none() && self.objectives.is_empty() {
|
||||
return s.serialize_str(text);
|
||||
}
|
||||
}
|
||||
let mut map = s.serialize_map(None)?;
|
||||
if let Some(v) = &self.reference {
|
||||
map.serialize_entry("ref", v)?;
|
||||
}
|
||||
if let Some(v) = &self.locator {
|
||||
map.serialize_entry("locator", v)?;
|
||||
}
|
||||
if let Some(v) = &self.path {
|
||||
map.serialize_entry("path", v)?;
|
||||
}
|
||||
if let Some(v) = &self.url {
|
||||
map.serialize_entry("url", v)?;
|
||||
}
|
||||
if self.role != ReadingRole::Assigned {
|
||||
map.serialize_entry("role", &self.role)?;
|
||||
}
|
||||
if !self.objectives.is_empty() {
|
||||
map.serialize_entry("objectives", &self.objectives)?;
|
||||
}
|
||||
if let Some(v) = &self.summary {
|
||||
map.serialize_entry("summary", v)?;
|
||||
}
|
||||
if let Some(v) = &self.focus {
|
||||
map.serialize_entry("focus", v)?;
|
||||
}
|
||||
if let Some(v) = &self.skip {
|
||||
map.serialize_entry("skip", v)?;
|
||||
}
|
||||
if let Some(v) = &self.text {
|
||||
map.serialize_entry("text", v)?;
|
||||
}
|
||||
map.end()
|
||||
}
|
||||
}
|
||||
|
||||
/// Accepts a reading written either as a mapping or as a bare string.
|
||||
///
|
||||
/// The string form is what `readings` held before this schema, so course files
|
||||
/// written against the old shape keep loading. It is the same courtesy
|
||||
/// [`yaml::flexible_string`] extends to an unquoted `schema_version: 1.0`.
|
||||
impl<'de> Deserialize<'de> for Reading {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Reading, D::Error> {
|
||||
/// The mapping form, with the field set kept in one place.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Mapping {
|
||||
#[serde(rename = "ref", default)]
|
||||
reference: Option<String>,
|
||||
#[serde(default)]
|
||||
locator: Option<String>,
|
||||
#[serde(default)]
|
||||
path: Option<String>,
|
||||
#[serde(default)]
|
||||
url: Option<String>,
|
||||
#[serde(default)]
|
||||
role: ReadingRole,
|
||||
#[serde(default)]
|
||||
objectives: Vec<String>,
|
||||
#[serde(default)]
|
||||
summary: Option<String>,
|
||||
#[serde(default)]
|
||||
focus: Option<String>,
|
||||
#[serde(default)]
|
||||
skip: Option<String>,
|
||||
#[serde(default)]
|
||||
text: Option<String>,
|
||||
}
|
||||
|
||||
struct V;
|
||||
impl<'a> Visitor<'a> for V {
|
||||
type Value = Reading;
|
||||
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("a reading mapping with a `ref`, or a plain citation string")
|
||||
}
|
||||
|
||||
fn visit_str<E: de::Error>(self, v: &str) -> std::result::Result<Reading, E> {
|
||||
Ok(Reading {
|
||||
text: Some(v.to_string()),
|
||||
..Reading::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn visit_map<M: MapAccess<'a>>(self, map: M) -> std::result::Result<Reading, M::Error> {
|
||||
let m = Mapping::deserialize(de::value::MapAccessDeserializer::new(map))?;
|
||||
Ok(Reading {
|
||||
reference: m.reference,
|
||||
locator: m.locator,
|
||||
path: m.path,
|
||||
url: m.url,
|
||||
role: m.role,
|
||||
objectives: m.objectives,
|
||||
summary: m.summary,
|
||||
focus: m.focus,
|
||||
skip: m.skip,
|
||||
text: m.text,
|
||||
})
|
||||
}
|
||||
}
|
||||
d.deserialize_any(V)
|
||||
}
|
||||
}
|
||||
|
||||
/// A learning objective.
|
||||
@@ -190,6 +508,15 @@ pub struct Objective {
|
||||
/// The lectures that develop it.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub lectures: Vec<String>,
|
||||
/// Position in teaching order, low first.
|
||||
///
|
||||
/// The registry is a map, so declaration order is lost on load, and sorting by
|
||||
/// id would put `lo-enthalpy` before `lo-first-law` when the second is a
|
||||
/// prerequisite of the first. Anything that prints objectives in the order you
|
||||
/// teach them, a lecture page above all, needs this. Objectives without it sort
|
||||
/// last, by id.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub order: Option<u32>,
|
||||
/// The highest level you intend to assess this objective at. Assembling an
|
||||
/// item above the ceiling is a warning: either the item overreaches or the
|
||||
/// ceiling needs raising.
|
||||
@@ -306,6 +633,25 @@ impl CourseFile {
|
||||
}
|
||||
}
|
||||
|
||||
let mut labels: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
|
||||
for (key, reference) in &self.references {
|
||||
if reference.title.trim().is_empty() {
|
||||
issues.push(format!("reference `{key}`: empty title"));
|
||||
}
|
||||
if let Some(label) = &reference.label {
|
||||
labels.entry(label.as_str()).or_default().push(key);
|
||||
}
|
||||
}
|
||||
for (label, keys) in &labels {
|
||||
if keys.len() > 1 {
|
||||
issues.push(format!(
|
||||
"references: `{label}` is the label of {}; a label has to name one work \
|
||||
because reports print it instead of the key",
|
||||
keys.join(" and ")
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
for (id, lec) in &self.lectures {
|
||||
if lec.title.trim().is_empty() {
|
||||
issues.push(format!("lecture `{id}`: empty title"));
|
||||
@@ -315,6 +661,10 @@ impl CourseFile {
|
||||
issues.push(format!("lecture `{id}`: unknown unit `{u}`"));
|
||||
}
|
||||
}
|
||||
let mut seen: Vec<(&str, &str)> = Vec::new();
|
||||
for (index, reading) in lec.readings.iter().enumerate() {
|
||||
issues.extend(self.reading_issues(id, index, reading, &mut seen));
|
||||
}
|
||||
}
|
||||
|
||||
for (id, lo) in &self.learning_objectives {
|
||||
@@ -347,6 +697,66 @@ impl CourseFile {
|
||||
issues
|
||||
}
|
||||
|
||||
/// Checks one reading, collecting every problem with it.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `lecture` - the lecture id, for the message.
|
||||
/// * `index` - position in the lecture's list, since a reading has no id.
|
||||
/// * `reading` - the reading.
|
||||
/// * `seen` - reference and locator pairs already found in this lecture,
|
||||
/// extended as it goes.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// One message per problem.
|
||||
fn reading_issues<'a>(
|
||||
&self,
|
||||
lecture: &str,
|
||||
index: usize,
|
||||
reading: &'a Reading,
|
||||
seen: &mut Vec<(&'a str, &'a str)>,
|
||||
) -> Vec<String> {
|
||||
let mut issues = Vec::new();
|
||||
let at = format!("lecture `{lecture}` reading {}", index + 1);
|
||||
|
||||
let Some(key) = reading.reference.as_deref() else {
|
||||
if reading.text.is_none() {
|
||||
issues.push(format!(
|
||||
"{at}: needs a `ref` naming a reference, or a plain citation string"
|
||||
));
|
||||
}
|
||||
return issues;
|
||||
};
|
||||
|
||||
match self.references.get(key) {
|
||||
None => issues.push(format!("{at}: unknown reference `{key}`")),
|
||||
Some(reference) => {
|
||||
if reading.path.is_some() && reference.base_url.is_none() && reading.url.is_none() {
|
||||
issues.push(format!(
|
||||
"{at}: has a `path` but reference `{key}` has no `base_url` to join it to"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(locator) = reading.locator.as_deref() {
|
||||
if seen.contains(&(key, locator)) {
|
||||
issues.push(format!(
|
||||
"{at}: `{key} {locator}` is assigned twice in one lecture"
|
||||
));
|
||||
}
|
||||
seen.push((key, locator));
|
||||
}
|
||||
|
||||
for objective in &reading.objectives {
|
||||
if !self.learning_objectives.contains_key(objective) {
|
||||
issues.push(format!("{at}: unknown learning objective `{objective}`"));
|
||||
}
|
||||
}
|
||||
issues
|
||||
}
|
||||
|
||||
/// Detects cycles in the objective prerequisite graph.
|
||||
///
|
||||
/// A cycle would make a study-order suggestion loop forever, so it is worth
|
||||
@@ -470,7 +880,8 @@ impl CourseFile {
|
||||
.unwrap_or_else(|| id.to_string())
|
||||
}
|
||||
|
||||
/// Objectives in a stable teaching order: by unit as declared, then by id.
|
||||
/// Objectives in a stable teaching order: by unit as declared, then by
|
||||
/// [`Objective::order`], then by id.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
@@ -490,11 +901,148 @@ impl CourseFile {
|
||||
.as_deref()
|
||||
.and_then(|u| unit_rank.get(u).copied())
|
||||
.unwrap_or(usize::MAX);
|
||||
(rank, (*id).clone())
|
||||
(rank, lo.order.unwrap_or(u32::MAX), (*id).clone())
|
||||
});
|
||||
ids.into_iter().cloned().collect()
|
||||
}
|
||||
|
||||
/// The objectives a lecture covers, in teaching order.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `lecture` - the lecture id.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Objective ids whose `lectures` list names this lecture, ordered by
|
||||
/// [`Objective::order`] and then by id.
|
||||
pub fn lecture_objectives(&self, lecture: &str) -> Vec<&str> {
|
||||
let mut ids: Vec<&String> = self
|
||||
.learning_objectives
|
||||
.iter()
|
||||
.filter(|(_, lo)| lo.lectures.iter().any(|l| l == lecture))
|
||||
.map(|(id, _)| id)
|
||||
.collect();
|
||||
ids.sort_by_key(|id| {
|
||||
let lo = &self.learning_objectives[*id];
|
||||
(lo.order.unwrap_or(u32::MAX), (*id).clone())
|
||||
});
|
||||
ids.into_iter().map(String::as_str).collect()
|
||||
}
|
||||
|
||||
/// Every reading that serves an objective, with the lecture it was assigned in.
|
||||
///
|
||||
/// Derived by scanning lectures rather than stored on the objective, for the
|
||||
/// same reason [`crate::history::History`] derives usage from assessment
|
||||
/// records: a second copy of an edge is a second thing to keep in step. It also
|
||||
/// puts the pointer on the volatile side, since a new edition renumbers
|
||||
/// sections but leaves your objectives alone.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `objective` - the objective id.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Pairs of lecture id and reading, in lecture order then assignment order.
|
||||
pub fn readings_for_objective(&self, objective: &str) -> Vec<(&str, &Reading)> {
|
||||
let mut out = Vec::new();
|
||||
for (lecture_id, lecture) in &self.lectures {
|
||||
for reading in &lecture.readings {
|
||||
if reading.objectives.iter().any(|o| o == objective) {
|
||||
out.push((lecture_id.as_str(), reading));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Assessed objectives with no reading behind them.
|
||||
///
|
||||
/// These are the objectives a student report cannot advise on: it can say the
|
||||
/// objective was missed, but not where to go and read about it.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Objective ids in teaching order.
|
||||
pub fn objectives_without_readings(&self) -> Vec<&str> {
|
||||
let cited: std::collections::BTreeSet<&str> = self
|
||||
.lectures
|
||||
.values()
|
||||
.flat_map(|l| l.readings.iter())
|
||||
.flat_map(|r| r.objectives.iter())
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
self.objectives_in_order()
|
||||
.into_iter()
|
||||
.filter_map(|id| {
|
||||
let (key, lo) = self.learning_objectives.get_key_value(&id)?;
|
||||
(lo.assessed && !cited.contains(key.as_str())).then_some(key.as_str())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Looks up a reference, erroring on a dangling citation key.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `key` - the citation key.
|
||||
/// * `context` - what cited it, for the error message.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The reference.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::Unresolved`] when the key is not registered.
|
||||
pub fn reference(&self, key: &str, context: &str) -> Result<&Reference> {
|
||||
self.references.get(key).ok_or_else(|| Error::Unresolved {
|
||||
kind: "reference",
|
||||
id: key.to_string(),
|
||||
context: Some(context.to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Expands `{objective-id}` in a prose field to whatever the caller wants.
|
||||
///
|
||||
/// Reading notes refer to objectives in passing ("a worked instance of
|
||||
/// `{lo-vdw-additivity}`"), and a lecture page renders that as a number while a
|
||||
/// student report renders it as text. Only a name that resolves to a declared
|
||||
/// objective is treated as a placeholder, so `$U_\text{final}$` passes through
|
||||
/// untouched; that collision is the reason this is not a general template
|
||||
/// syntax.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `prose` - the field to expand.
|
||||
/// * `render` - called with each resolved objective id.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The prose with resolved placeholders replaced.
|
||||
pub fn expand_objective_refs(&self, prose: &str, render: impl Fn(&str) -> String) -> String {
|
||||
let mut out = String::with_capacity(prose.len());
|
||||
let mut rest = prose;
|
||||
while let Some(open) = rest.find('{') {
|
||||
let (head, tail) = rest.split_at(open);
|
||||
out.push_str(head);
|
||||
let Some(close) = tail.find('}') else {
|
||||
out.push_str(tail);
|
||||
return out;
|
||||
};
|
||||
let name = &tail[1..close];
|
||||
if self.learning_objectives.contains_key(name) {
|
||||
out.push_str(&render(name));
|
||||
} else {
|
||||
out.push_str(&tail[..=close]);
|
||||
}
|
||||
rest = &tail[close + 1..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// A skeleton course file for `coursebank init`.
|
||||
///
|
||||
/// # Arguments
|
||||
@@ -525,6 +1073,7 @@ impl CourseFile {
|
||||
text: "Replace this with an objective stated as a student action.".to_string(),
|
||||
unit: Some("u-intro".to_string()),
|
||||
lectures: vec!["L01".to_string()],
|
||||
order: Some(1),
|
||||
level_ceiling: Some(Level::Understand),
|
||||
prerequisites: Vec::new(),
|
||||
tags: Vec::new(),
|
||||
@@ -549,6 +1098,7 @@ impl CourseFile {
|
||||
}],
|
||||
lectures,
|
||||
learning_objectives: los,
|
||||
references: BTreeMap::new(),
|
||||
stimuli: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
@@ -706,4 +1256,215 @@ learning_objectives:
|
||||
assert_eq!(slugify("Exam 4 -- Final!"), "exam-4-final");
|
||||
assert_eq!(slugify(" "), "");
|
||||
}
|
||||
|
||||
/// A course with one reference and two readings, one of them supplemental.
|
||||
fn with_readings() -> CourseFile {
|
||||
parse(
|
||||
r#"
|
||||
course: { code: X, title: Y, term: Z }
|
||||
references:
|
||||
kuriyan2013molecules:
|
||||
label: KKW
|
||||
role: required
|
||||
title: The molecules of life
|
||||
base_url: https://example.org/kkw/
|
||||
lectures:
|
||||
L1.1:
|
||||
title: Enthalpy
|
||||
readings:
|
||||
- ref: kuriyan2013molecules
|
||||
locator: '§6.1'
|
||||
path: '6/A/#1'
|
||||
objectives: [lo-a]
|
||||
summary: What a system is.
|
||||
focus: Fix the definitions.
|
||||
- ref: kuriyan2013molecules
|
||||
locator: '§1.9'
|
||||
path: '1/B/#9'
|
||||
role: supplemental
|
||||
objectives: [lo-b]
|
||||
learning_objectives:
|
||||
lo-a: { text: A, lectures: [L1.1], order: 1 }
|
||||
lo-b: { text: B, lectures: [L1.1], order: 2 }
|
||||
"#,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_structured_reading_parses_and_validates() {
|
||||
let c = with_readings();
|
||||
assert!(c.validate().is_empty(), "{:?}", c.validate());
|
||||
let readings = &c.lectures["L1.1"].readings;
|
||||
assert_eq!(
|
||||
readings[0].reference.as_deref(),
|
||||
Some("kuriyan2013molecules")
|
||||
);
|
||||
assert_eq!(readings[0].role, ReadingRole::Assigned);
|
||||
assert_eq!(readings[1].role, ReadingRole::Supplemental);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reading_url_is_built_from_the_reference_base() {
|
||||
let c = with_readings();
|
||||
let reference = &c.references["kuriyan2013molecules"];
|
||||
let reading = &c.lectures["L1.1"].readings[0];
|
||||
assert_eq!(
|
||||
reading.resolve_url(reference).as_deref(),
|
||||
Some("https://example.org/kkw/6/A/#1")
|
||||
);
|
||||
assert_eq!(reading.cite("kuriyan2013molecules", reference), "KKW §6.1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_string_reading_still_parses_and_round_trips() {
|
||||
let c = parse(
|
||||
r#"
|
||||
course: { code: X, title: Y, term: Z }
|
||||
lectures:
|
||||
L01:
|
||||
title: One
|
||||
readings:
|
||||
- 'KKW §6.1: system and surroundings. https://example.org/1'
|
||||
"#,
|
||||
);
|
||||
let reading = &c.lectures["L01"].readings[0];
|
||||
assert!(reading.reference.is_none());
|
||||
assert_eq!(
|
||||
reading.text.as_deref(),
|
||||
Some("KKW §6.1: system and surroundings. https://example.org/1")
|
||||
);
|
||||
assert!(c.validate().is_empty());
|
||||
|
||||
// Serializing writes the string back as a string, so a load-and-save cycle
|
||||
// does not migrate a file the author has not chosen to migrate.
|
||||
let yaml = serde_yaml_ng::to_string(&c).expect("serializes");
|
||||
assert!(yaml.contains("- 'KKW §6.1: system and surroundings. https://example.org/1'"));
|
||||
assert!(!yaml.contains("text:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readings_resolve_backwards_from_an_objective() {
|
||||
let c = with_readings();
|
||||
let found = c.readings_for_objective("lo-a");
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(found[0].0, "L1.1");
|
||||
assert_eq!(found[0].1.locator.as_deref(), Some("§6.1"));
|
||||
assert!(c.readings_for_objective("lo-nobody").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_objective_with_no_reading_is_reported() {
|
||||
let mut c = with_readings();
|
||||
assert!(c.objectives_without_readings().is_empty());
|
||||
c.learning_objectives.insert(
|
||||
"lo-orphan".to_string(),
|
||||
Objective {
|
||||
text: "Orphan".to_string(),
|
||||
unit: None,
|
||||
lectures: vec!["L1.1".to_string()],
|
||||
order: Some(3),
|
||||
level_ceiling: None,
|
||||
prerequisites: Vec::new(),
|
||||
tags: Vec::new(),
|
||||
assessed: true,
|
||||
},
|
||||
);
|
||||
assert_eq!(c.objectives_without_readings(), vec!["lo-orphan"]);
|
||||
|
||||
// An objective you teach but do not test is not a gap.
|
||||
c.learning_objectives
|
||||
.get_mut("lo-orphan")
|
||||
.expect("just inserted")
|
||||
.assessed = false;
|
||||
assert!(c.objectives_without_readings().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objective_order_beats_id_order_within_a_lecture() {
|
||||
let c = parse(
|
||||
r#"
|
||||
course: { code: X, title: Y, term: Z }
|
||||
lectures:
|
||||
L1.1: { title: One }
|
||||
learning_objectives:
|
||||
lo-enthalpy: { text: Third, lectures: [L1.1], order: 3 }
|
||||
lo-first-law: { text: Second, lectures: [L1.1], order: 2 }
|
||||
lo-system: { text: First, lectures: [L1.1], order: 1 }
|
||||
"#,
|
||||
);
|
||||
// Alphabetically this is enthalpy, first-law, system, which puts an
|
||||
// objective ahead of its own prerequisite.
|
||||
assert_eq!(
|
||||
c.lecture_objectives("L1.1"),
|
||||
vec!["lo-system", "lo-first-law", "lo-enthalpy"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_references_and_objectives_on_a_reading_are_reported() {
|
||||
let c = parse(
|
||||
r#"
|
||||
course: { code: X, title: Y, term: Z }
|
||||
references:
|
||||
known: { title: A book }
|
||||
lectures:
|
||||
L01:
|
||||
title: One
|
||||
readings:
|
||||
- { ref: missing, locator: '§1' }
|
||||
- { ref: known, locator: '§2', path: '2/', objectives: [lo-nope] }
|
||||
"#,
|
||||
);
|
||||
let issues = c.validate();
|
||||
assert!(
|
||||
issues
|
||||
.iter()
|
||||
.any(|i| i.contains("unknown reference `missing`"))
|
||||
);
|
||||
assert!(
|
||||
issues
|
||||
.iter()
|
||||
.any(|i| i.contains("unknown learning objective `lo-nope`"))
|
||||
);
|
||||
// `path` with no base_url to join it to.
|
||||
assert!(issues.iter().any(|i| i.contains("base_url")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_duplicate_label_and_a_duplicate_locator_are_reported() {
|
||||
let c = parse(
|
||||
r#"
|
||||
course: { code: X, title: Y, term: Z }
|
||||
references:
|
||||
one: { title: First, label: KKW }
|
||||
two: { title: Second, label: KKW }
|
||||
lectures:
|
||||
L01:
|
||||
title: One
|
||||
readings:
|
||||
- { ref: one, locator: '§1' }
|
||||
- { ref: one, locator: '§1' }
|
||||
"#,
|
||||
);
|
||||
let issues = c.validate();
|
||||
assert!(issues.iter().any(|i| i.contains("`KKW` is the label of")));
|
||||
assert!(
|
||||
issues
|
||||
.iter()
|
||||
.any(|i| i.contains("assigned twice in one lecture"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_declared_objective_id_is_a_placeholder() {
|
||||
let c = with_readings();
|
||||
let expanded = c.expand_objective_refs(
|
||||
r"a worked instance of {lo-a}, where $U_\text{final}$ is unchanged, {lo-typo} too",
|
||||
|id| format!("<{id}>"),
|
||||
);
|
||||
assert_eq!(
|
||||
expanded,
|
||||
r"a worked instance of <lo-a>, where $U_\text{final}$ is unchanged, {lo-typo} too"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user