feat: initial package draft

This commit is contained in:
2026-08-05 23:18:16 -04:00
parent 66291ba545
commit 09c3222f8d
36 changed files with 21604 additions and 0 deletions
+518
View File
@@ -0,0 +1,518 @@
//! Rendering a printed exam with Typst.
//!
//! Typst rather than LaTeX because the toolchain is one binary with no package
//! manager, the error messages point at a line, and the compile is fast enough to
//! iterate on. `pixi run -e docs typst compile` turns the output of this module
//! into a PDF.
//!
//! The emitted document is deliberately plain and self-contained: no imports, no
//! template packages, nothing that can break because a package version moved. It
//! is also meant to be edited. A generated exam is a starting point, and the
//! output is formatted so that a human can reasonably open it and adjust spacing
//! before printing.
//!
//! Every export takes a form, so form B's answer key is generated from the same
//! permutation that produced form B's question paper. Keeping the key and the
//! paper in one code path is the only way to be sure they agree — a mismatch is
//! discovered by twenty-five students at once.
use crate::assessment::{AssessmentFile, Form};
use crate::catalog::Catalog;
use crate::course::CourseFile;
use crate::error::{Error, Result};
use crate::markup;
use crate::select;
/// Options for a printed exam.
#[derive(Debug, Clone)]
pub struct Options {
/// Which form to render.
pub form: Form,
/// Whether to leave a name and student-id block at the top.
pub name_block: bool,
/// Whether to show the points each question is worth.
pub show_points: bool,
/// Whether to start each question on a new page. Occasionally worth it for an
/// exam with long stimuli.
pub page_per_item: bool,
/// Paper size, as Typst names it.
pub paper: String,
/// Base font size.
pub font_size: String,
}
impl Default for Options {
fn default() -> Options {
Options {
form: Form {
id: "A".to_string(),
seed: 0,
shuffle_items: false,
shuffle_options: false,
},
name_block: true,
show_points: true,
page_per_item: false,
paper: "us-letter".to_string(),
font_size: "11pt".to_string(),
}
}
}
/// Renders the question paper.
///
/// # Arguments
///
/// * `catalog` - the loaded course.
/// * `record` - the assessment record.
/// * `opts` - rendering options.
///
/// # Returns
///
/// A complete Typst document.
///
/// # Errors
///
/// Returns [`Error::Unresolved`] when a placement references a missing item.
pub fn exam(catalog: &Catalog, record: &AssessmentFile, opts: &Options) -> Result<String> {
let course = &catalog.course;
let mut out = String::new();
out.push_str(&preamble(course, record, opts));
if opts.name_block {
out.push_str(
"#block(above: 1em, below: 1.5em)[\n \
#grid(columns: (auto, 1fr, auto, 1fr), gutter: 0.6em,\n \
[*Name*], [#box(width: 100%, repeat[.])],\n \
[*Student ID*], [#box(width: 100%, repeat[.])],\n )\n]\n\n",
);
}
if let Some(instructions) = &record.assessment.instructions {
out.push_str(&format!(
"#block(fill: luma(245), inset: 8pt, radius: 3pt, width: 100%)[\n {}\n]\n\n",
markup::to_typst(instructions)
));
}
let default_points = course.policy.points_per_item;
let mut printed = 0usize;
for placement in select::layout(record, &opts.form) {
if placement.dropped {
continue;
}
let entry = catalog.require(&placement.item)?;
let item = &entry.item;
printed += 1;
if opts.page_per_item && printed > 1 {
out.push_str("#pagebreak()\n\n");
}
// A stimulus shared by several items is printed with each of them. That
// repeats material, but a student should never have to flip pages to find
// the passage a question refers to.
if let Some(id) = &item.stimulus {
if let Some(stimulus) = course.stimuli.get(id) {
out.push_str(&format!(
"#block(stroke: 0.5pt + luma(180), inset: 8pt, radius: 3pt, width: 100%)[\n \
{}\n]\n",
markup::to_typst(&stimulus.body)
));
if let Some(caption) = &stimulus.caption {
out.push_str(&format!(
"#block(above: 0.3em)[#text(size: 0.85em, style: \"italic\")[{}]]\n",
markup::to_typst(caption)
));
}
}
}
let points = placement
.points
.unwrap_or_else(|| item.points(default_points));
let label = if placement.bonus {
if opts.show_points {
format!(
" #text(fill: rgb(\"#666666\"))[(bonus, {})]",
plural_points(points)
)
} else {
" #text(fill: rgb(\"#666666\"))[(bonus)]".to_string()
}
} else if opts.show_points {
format!(
" #text(fill: rgb(\"#666666\"))[({})]",
plural_points(points)
)
} else {
String::new()
};
// The question number is the recorded one, not the printed position, so a
// scanned answer sheet still joins to the assessment record.
out.push_str(&format!(
"#block(above: 1.2em, below: 0.5em)[*{}.*{label} {}]\n",
placement.number,
markup::to_typst(&item.stem)
));
if item.is_multi_key() {
out.push_str(
"#block(below: 0.4em)[#text(size: 0.9em, style: \"italic\")[Select all that \
apply.]]\n",
);
}
let order = select::option_order(&opts.form, &placement.item, item.options.len());
out.push_str("#block(inset: (left: 1.2em))[\n");
for (position, source_index) in order.iter().enumerate() {
let choice = &item.options[*source_index];
// Options are relabeled by printed position, so a shuffled form still
// reads A, B, C, D.
let letter = (b'A' + position as u8) as char;
out.push_str(&format!(
" #grid(columns: (1.4em, 1fr), gutter: 0.2em)[{letter}.][{}]\n",
markup::to_typst(&choice.text)
));
}
out.push_str("]\n\n");
}
if printed == 0 {
return Err(Error::Invalid(vec![
"this assessment has no printable items; every placement is marked dropped".to_string(),
]));
}
Ok(out)
}
/// Renders the answer key.
///
/// # Arguments
///
/// * `catalog` - the loaded course.
/// * `record` - the assessment record.
/// * `opts` - rendering options, whose form determines the letters.
///
/// # Returns
///
/// A complete Typst document.
///
/// # Errors
///
/// Returns [`Error::Unresolved`] when a placement references a missing item.
pub fn answer_key(catalog: &Catalog, record: &AssessmentFile, opts: &Options) -> Result<String> {
let mut out = String::new();
out.push_str(&format!(
"#set page(paper: \"{}\", margin: 2cm)\n#set text(size: 10pt)\n\n\
= {} — answer key (form {})\n\n",
opts.paper,
escape(&record.assessment.title),
opts.form.id
));
out.push_str(
"#text(size: 0.9em, style: \"italic\")[Letters below are the letters *as printed on this \
form*. Do not use this key on another form.]\n\n",
);
out.push_str(
"#table(\n columns: (auto, auto, auto, 1fr),\n align: (right, center, center, left),\n \
table.header([*\\#*], [*Key*], [*Level*], [*Objectives*]),\n",
);
for placement in select::layout(record, &opts.form) {
if placement.dropped {
continue;
}
let entry = catalog.require(&placement.item)?;
let item = &entry.item;
let order = select::option_order(&opts.form, &placement.item, item.options.len());
// Map the source option index to the letter it was printed as.
let mut printed_letters = Vec::new();
for (position, source_index) in order.iter().enumerate() {
if item.options[*source_index].correct {
printed_letters.push(((b'A' + position as u8) as char).to_string());
}
}
let objectives = if placement.learning_objectives.is_empty() {
item.learning_objectives.join(", ")
} else {
placement.learning_objectives.join(", ")
};
out.push_str(&format!(
" [{}], [*{}*], [{}], [{}],\n",
placement.number,
printed_letters.join(""),
placement
.level
.map(|l| l.code().to_string())
.unwrap_or_else(|| "-".into()),
escape(&objectives)
));
}
out.push_str(")\n\n");
// Partial credit decisions belong on the key, where the grader will see them.
let overrides: Vec<String> = record
.items
.iter()
.filter(|p| !p.credit_overrides.is_empty())
.map(|p| {
let list: Vec<String> = p
.credit_overrides
.iter()
.map(|(letter, credit)| format!("{letter} = {:.0}%", credit * 100.0))
.collect();
format!("Question {}: {}", p.number, list.join(", "))
})
.collect();
if !overrides.is_empty() {
out.push_str("== Partial credit\n\n");
for line in overrides {
out.push_str(&format!("- {}\n", escape(&line)));
}
out.push('\n');
}
let dropped: Vec<String> = record
.items
.iter()
.filter(|p| p.dropped)
.map(|p| p.number.to_string())
.collect();
if !dropped.is_empty() {
out.push_str(&format!(
"== Dropped\n\nQuestion(s) {} were dropped and are not printed.\n\n",
dropped.join(", ")
));
}
Ok(out)
}
/// Renders a bubble sheet matching the form.
///
/// # Arguments
///
/// * `catalog` - the loaded course, for option counts.
/// * `record` - the assessment record.
/// * `opts` - rendering options.
///
/// # Returns
///
/// A complete Typst document.
///
/// # Errors
///
/// Returns [`Error::Unresolved`] when a placement references a missing item.
pub fn bubble_sheet(catalog: &Catalog, record: &AssessmentFile, opts: &Options) -> Result<String> {
let mut out = format!(
"#set page(paper: \"{}\", margin: 1.5cm)\n#set text(size: 10pt)\n\n\
= {} — answer sheet (form {})\n\n\
#grid(columns: (auto, 1fr, auto, 1fr), gutter: 0.6em,\n \
[*Name*], [#box(width: 100%, repeat[.])],\n \
[*Student ID*], [#box(width: 100%, repeat[.])],\n)\n\n\
#v(1em)\n",
opts.paper,
escape(&record.assessment.title),
opts.form.id
);
out.push_str("#columns(2)[\n");
for placement in select::layout(record, &opts.form) {
if placement.dropped {
continue;
}
let entry = catalog.require(&placement.item)?;
let count = entry.item.options.len();
let bubbles: Vec<String> = (0..count)
.map(|i| {
let letter = (b'A' + i as u8) as char;
format!("#circle(radius: 0.42em, stroke: 0.5pt)[#align(center + horizon)[#text(size: 0.7em)[{letter}]]]")
})
.collect();
out.push_str(&format!(
" #block(below: 0.45em)[#box(width: 2em)[{}.] {}]\n",
placement.number,
bubbles.join(" ")
));
}
out.push_str("]\n");
Ok(out)
}
/// Builds the document preamble.
///
/// # Arguments
///
/// * `course` - the course.
/// * `record` - the assessment record.
/// * `opts` - rendering options.
///
/// # Returns
///
/// Typst setup and a title block.
fn preamble(course: &CourseFile, record: &AssessmentFile, opts: &Options) -> String {
let form_note = if record.forms.len() > 1 {
format!(" · Form {}", opts.form.id)
} else {
String::new()
};
let date = record
.assessment
.date
.map(|d| d.to_string())
.unwrap_or_default();
let minutes = record
.assessment
.minutes_allowed
.map(|m| format!(" · {m:.0} minutes"))
.unwrap_or_default();
format!(
"#set page(\n paper: \"{paper}\",\n margin: 2cm,\n \
header: [#text(size: 0.85em)[{code} · {title}{form_note}]],\n \
footer: context [#text(size: 0.85em)[Page #counter(page).display() of \
#counter(page).final().first()]],\n)\n\
#set text(size: {size})\n\
#set par(justify: false, leading: 0.65em)\n\n\
#align(center)[\n #text(size: 1.4em, weight: \"bold\")[{title}]\n \\\n \
#text(size: 0.95em)[{code}{course_title} · {term}]\n \\\n \
#text(size: 0.9em)[{date}{minutes}]\n]\n\n",
paper = opts.paper,
size = opts.font_size,
code = escape(&course.course.code),
course_title = escape(&course.course.title),
term = escape(
record
.assessment
.term
.as_deref()
.unwrap_or(&course.course.term)
),
title = escape(&record.assessment.title),
form_note = form_note,
date = date,
minutes = minutes,
)
}
/// Formats a point value with the right plural.
fn plural_points(points: f64) -> String {
if (points - 1.0).abs() < 1e-9 {
"1 point".to_string()
} else if (points.fract()).abs() < 1e-9 {
format!("{points:.0} points")
} else {
format!("{points} points")
}
}
/// Escapes text for Typst content mode.
fn escape(s: &str) -> String {
markup::to_typst(s)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::assessment::Placement;
#[test]
fn point_labels_are_pluralized() {
assert_eq!(plural_points(1.0), "1 point");
assert_eq!(plural_points(2.0), "2 points");
assert_eq!(plural_points(1.5), "1.5 points");
}
#[test]
fn escaping_protects_typst_syntax() {
assert_eq!(escape("email me @ home"), "email me \\@ home");
assert_eq!(escape("a < b"), "a \\< b");
}
#[test]
fn the_key_reports_letters_as_printed() {
// Shuffling must relabel the key: if the correct option moves to the third
// printed position, the key says C.
let form = Form {
id: "B".into(),
seed: 99,
shuffle_items: false,
shuffle_options: true,
};
let order = select::option_order(&form, "bank::q-1", 4);
let correct_source = 0usize;
let printed_position = order.iter().position(|i| *i == correct_source).unwrap();
let letter = (b'A' + printed_position as u8) as char;
assert!(('A'..='D').contains(&letter));
// And it is reproducible.
let again = select::option_order(&form, "bank::q-1", 4);
assert_eq!(order, again);
}
#[test]
fn dropped_items_are_not_printed() {
let record = AssessmentFile {
schema_version: "1.0".into(),
assessment: crate::assessment::Assessment {
id: "e1".into(),
title: "Exam 1".into(),
term: None,
kind: crate::assessment::Kind::Exam,
date: None,
platform: crate::assessment::Platform::Paper,
minutes_allowed: None,
attempts: None,
shuffle: None,
scoring_policy: None,
instructions: None,
notes: None,
},
blueprint: None,
forms: Vec::new(),
items: vec![
Placement {
number: 1,
item: "b::q-1".into(),
version: None,
fingerprint: None,
points: None,
bonus: false,
key: vec!["A".into()],
level: None,
learning_objectives: Vec::new(),
credit_overrides: Default::default(),
dropped: true,
},
Placement {
number: 2,
item: "b::q-2".into(),
version: None,
fingerprint: None,
points: None,
bonus: false,
key: vec!["B".into()],
level: None,
learning_objectives: Vec::new(),
credit_overrides: Default::default(),
dropped: false,
},
],
};
let printable: Vec<u32> = select::layout(&record, &Options::default().form)
.into_iter()
.filter(|p| !p.dropped)
.map(|p| p.number)
.collect();
assert_eq!(printable, vec![2]);
}
}