//! Generated pages: collection listings and tag pages. //! //! Generated pages have no Markdown source. They are built from config and //! the public pages, then rendered through the same template engine. Their //! routes are added to the link graph so wikilinks can target them. use std::collections::{BTreeMap, BTreeSet, HashMap}; use crate::config::{Collection, Config, Order}; use crate::content::Document; use crate::template::Value; /// A tag page target. #[derive(Debug, Clone)] pub struct TagTarget { pub label: String, pub slug: String, } /// A generated route that wikilinks can target. #[derive(Debug, Clone)] pub struct LinkTarget { pub route: String, pub title: String, pub tag: Option, } /// A generated page ready to render. #[derive(Debug)] pub struct Page { pub route: String, pub title: String, pub template: String, pub values: HashMap, pub tag: Option, } /// All generated pages for a build. #[derive(Debug)] pub struct Site { pub pages: Vec, } impl Site { pub fn link_targets(&self) -> Vec { self.pages .iter() .map(|page| LinkTarget { route: page.route.clone(), title: page.title.clone(), tag: page.tag.clone(), }) .collect() } } /// Build collection listings and tag pages. #[cfg(test)] pub fn build(config: &Config, documents: &[Document]) -> Result { build_with(config, documents, &HashMap::new()) } /// Build collection listings and tag pages with per-route backlink counts. pub fn build_with( config: &Config, documents: &[Document], backlinks: &HashMap, ) -> Result { let mut routes: HashMap = HashMap::new(); for document in documents { routes.insert(document.route.clone(), document.relative.clone()); } let mut pages = Vec::new(); for collection in &config.collections { let page = collection_page(config, documents, collection, backlinks)?; insert_route( &mut routes, &page.route, &format!("collection {}", collection.name), )?; pages.push(page); } for page in tag_pages(config, documents, backlinks)? { let owner = match &page.tag { Some(tag) => format!("tag {}", tag.label), None => "tag index".to_string(), }; insert_route(&mut routes, &page.route, &owner)?; pages.push(page); } Ok(Site { pages }) } fn insert_route( routes: &mut HashMap, route: &str, owner: &str, ) -> Result<(), String> { if let Some(existing) = routes.insert(route.to_string(), owner.to_string()) { return Err(format!( "{owner}: generated route {route} is already used by {existing}" )); } Ok(()) } fn collection_page( config: &Config, documents: &[Document], collection: &Collection, backlinks: &HashMap, ) -> Result { let prefix = collection_prefix(config, collection)?; let mut items: Vec<&Document> = documents .iter() .filter(|document| under_prefix(&document.relative, &prefix)) .collect(); sort_items(&mut items, collection.order); let base = base_for(&collection.route); let rows = items .iter() .map(|document| item_row(document, &base, backlinks)) .collect(); let mut values = page_values(config, &collection.title, &collection.route, &base, rows); values.insert( "collection".to_string(), Value::Str(collection.name.clone()), ); Ok(Page { route: collection.route.clone(), title: collection.title.clone(), template: collection.template.clone(), values, tag: None, }) } fn collection_prefix(config: &Config, collection: &Collection) -> Result { let relative = collection.path.strip_prefix(&config.content).map_err(|_| { format!( "collection {}: path {} is not inside the content directory {}", collection.name, collection.path.display(), config.content.display() ) })?; let prefix = relative .components() .filter_map(|component| match component { std::path::Component::Normal(value) => Some(value.to_string_lossy().into_owned()), _ => None, }) .collect::>() .join("/"); Ok(prefix) } fn under_prefix(relative: &str, prefix: &str) -> bool { prefix.is_empty() || relative.starts_with(&format!("{prefix}/")) } fn sort_items(items: &mut Vec<&Document>, order: Order) { items.sort_by(|left, right| match order { Order::Path => left.relative.cmp(&right.relative), Order::Title => left .title .to_lowercase() .cmp(&right.title.to_lowercase()) .then_with(|| left.route.cmp(&right.route)), Order::DateDesc | Order::DateAsc => match (left.date(), right.date()) { (Some(left_date), Some(right_date)) => { let ordering = left_date.cmp(right_date); let ordering = if order == Order::DateDesc { ordering.reverse() } else { ordering }; ordering.then_with(|| left.route.cmp(&right.route)) } (Some(_), None) => std::cmp::Ordering::Less, (None, Some(_)) => std::cmp::Ordering::Greater, (None, None) => left.route.cmp(&right.route), }, }); } fn item_row( document: &Document, base: &str, backlinks: &HashMap, ) -> BTreeMap { let mut row = BTreeMap::new(); row.insert("title".to_string(), document.title.clone()); row.insert("route".to_string(), document.route.clone()); row.insert("href".to_string(), relative_href(base, &document.route)); row.insert( "date".to_string(), document.date().unwrap_or("").to_string(), ); row.insert( "id".to_string(), document .meta .get("id") .and_then(crate::content::Value::as_str) .unwrap_or("") .to_string(), ); row.insert( "backlinks".to_string(), backlinks .get(&document.route) .copied() .unwrap_or(0) .to_string(), ); row.insert("tags".to_string(), document.tags().join(", ")); row.insert("source".to_string(), document.relative.clone()); row } fn tag_pages( config: &Config, documents: &[Document], backlinks: &HashMap, ) -> Result, String> { let mut groups: BTreeMap = BTreeMap::new(); let mut seen: BTreeSet = BTreeSet::new(); for (index, document) in documents.iter().enumerate() { seen.clear(); for tag in document.tags() { let label = tag.trim(); if label.is_empty() { continue; } let key = label.to_lowercase(); if !seen.insert(key.clone()) { continue; } groups .entry(key) .or_insert_with(|| TagGroup { label: label.to_string(), documents: Vec::new(), }) .documents .push(index); } } if groups.is_empty() { return Ok(Vec::new()); } let mut slugs: BTreeMap = BTreeMap::new(); let mut slug_by_key: HashMap = HashMap::new(); for (key, group) in &groups { let slug = tag_slug(&group.label); if slug.is_empty() { return Err(format!( "tag `{}` has no letters or digits to form a URL", group.label )); } if let Some(existing) = slugs.insert(slug.clone(), key.clone()) { if existing != *key { return Err(format!( "tags `{}` and `{}` both become /{}/", groups[&existing].label, group.label, slug )); } } slug_by_key.insert(key.clone(), slug); } let mut keys: Vec = groups.keys().cloned().collect(); keys.sort_by(|left, right| { groups[left] .label .to_lowercase() .cmp(&groups[right].label.to_lowercase()) }); let index_route = config.tags.route.clone(); let index_base = base_for(&index_route); let mut index_rows = Vec::with_capacity(keys.len()); for key in &keys { let group = &groups[key]; let slug = &slug_by_key[key]; let route = format!("{}{}/", config.tags.route, slug); let mut row = BTreeMap::new(); row.insert("tag".to_string(), group.label.clone()); row.insert("slug".to_string(), slug.clone()); row.insert("count".to_string(), group.documents.len().to_string()); row.insert("route".to_string(), route.clone()); row.insert("href".to_string(), relative_href(&index_base, &route)); index_rows.push(row); } let mut pages = Vec::new(); pages.push(Page { route: index_route.clone(), title: "Tags".to_string(), template: config.tags.index_template.clone(), values: page_values(config, "Tags", &index_route, &index_base, index_rows), tag: None, }); for key in keys { let group = &groups[&key]; let slug = slug_by_key[&key].clone(); let route = format!("{}{}/", config.tags.route, slug); let base = base_for(&route); let mut items: Vec<&Document> = group .documents .iter() .map(|index| &documents[*index]) .collect(); sort_items(&mut items, Order::Title); let rows = items .iter() .map(|document| item_row(document, &base, backlinks)) .collect(); let mut values = page_values(config, &group.label, &route, &base, rows); values.insert("tag".to_string(), Value::Str(group.label.clone())); values.insert("slug".to_string(), Value::Str(slug.clone())); pages.push(Page { route, title: group.label.clone(), template: config.tags.template.clone(), values, tag: Some(TagTarget { label: group.label.clone(), slug, }), }); } Ok(pages) } struct TagGroup { label: String, documents: Vec, } /// An ASCII tag slug: lowercase letters, digits and hyphens. pub fn tag_slug(label: &str) -> String { let mut output = String::new(); let mut pending = false; for ch in label.chars() { if ch.is_ascii_alphanumeric() { if pending && !output.is_empty() { output.push('-'); } pending = false; output.push(ch.to_ascii_lowercase()); } else if (ch.is_whitespace() || ch == '-' || ch == '_') && !output.is_empty() { pending = true; } } output } fn page_values( config: &Config, title: &str, route: &str, base: &str, items: Vec>, ) -> HashMap { let mut values = HashMap::new(); values.insert("site".to_string(), Value::Str(config.title.clone())); values.insert("lang".to_string(), Value::Str(config.lang.clone())); values.insert("title".to_string(), Value::Str(title.to_string())); values.insert("route".to_string(), Value::Str(route.to_string())); values.insert("base".to_string(), Value::Str(base.to_string())); values.insert("content".to_string(), Value::Str(String::new())); values.insert("backlinks".to_string(), Value::Str(String::new())); values.insert("count".to_string(), Value::Str(items.len().to_string())); values.insert( "items".to_string(), Value::List(items.into_iter().map(Value::Map).collect()), ); values } pub(crate) fn base_for(route: &str) -> String { let depth = route .trim_matches('/') .split('/') .filter(|part| !part.is_empty()) .count(); "../".repeat(depth) } pub(crate) fn relative_href(base: &str, route: &str) -> String { let mut href = format!("{}{}", base, route.trim_start_matches('/')); if href.is_empty() { href.push('.'); } href } #[cfg(test)] mod tests { use super::*; use std::collections::BTreeMap as Map; fn document( relative: &str, route: &str, title: &str, date: Option<&str>, tags: &[&str], ) -> Document { let mut meta = Map::new(); if let Some(date) = date { meta.insert( "date".to_string(), crate::content::Value::Str(date.to_string()), ); } if !tags.is_empty() { meta.insert( "tags".to_string(), crate::content::Value::List(tags.iter().map(|tag| tag.to_string()).collect()), ); } Document { relative: relative.to_string(), route: route.to_string(), body: String::new(), meta, title: title.to_string(), draft: false, template: None, aliases: Vec::new(), } } fn config_with(collections: Vec) -> Config { Config { title: "Test".to_string(), lang: "en".to_string(), content: std::path::PathBuf::from("/site/content"), templates: std::path::PathBuf::from("/site/templates"), static_dir: std::path::PathBuf::from("/site/static"), data: std::path::PathBuf::from("/site/data"), out: std::path::PathBuf::from("/site/site"), collections, tags: crate::config::Tags { route: "/tags/".to_string(), template: "tag.html".to_string(), index_template: "tags.html".to_string(), }, routes: crate::content::RouteMode::Slugify, ignore: Vec::new(), attachments: true, theme: crate::theme::Theme::UteriNight, pre_build_hook: None, standard_site: None, context_hook: None, root: std::path::PathBuf::from("/site"), } } fn collection(name: &str, path: &str, route: &str, order: Order) -> Collection { Collection { name: name.to_string(), title: name.to_string(), path: std::path::Path::new("/site/content").join(path), route: route.to_string(), template: "list.html".to_string(), order, } } fn titles(page: &Page) -> Vec { match page.values.get("items") { Some(Value::List(items)) => items .iter() .map(|item| match item { Value::Map(row) => row["title"].clone(), _ => String::new(), }) .collect(), _ => Vec::new(), } } #[test] fn listing_contains_pages_under_the_prefix() { let documents = vec![ document("notes/a.md", "/notes/a/", "A", None, &[]), document("notes/b.md", "/notes/b/", "B", None, &[]), document("other.md", "/other/", "Other", None, &[]), ]; let config = config_with(vec![collection("notes", "notes", "/notes/", Order::Path)]); let site = build(&config, &documents).unwrap(); assert_eq!(site.pages.len(), 1); let items = match site.pages[0].values.get("items") { Some(Value::List(items)) => items, _ => panic!("items missing"), }; assert_eq!(items.len(), 2); } #[test] fn rows_expose_id_and_backlink_count() { let mut source = document("n/a.md", "/n/a/", "A", None, &[]); source.meta.insert( "id".to_string(), crate::content::Value::Str("A1".to_string()), ); let mut counts = HashMap::new(); counts.insert("/n/a/".to_string(), 2usize); let config = config_with(vec![collection("n", "n", "/n/", Order::Path)]); let site = build_with(&config, &[source], &counts).unwrap(); let items = match site.pages[0].values.get("items") { Some(Value::List(items)) => items, _ => panic!("items missing"), }; let row = match &items[0] { Value::Map(row) => row, _ => panic!("expected a row"), }; assert_eq!(row["id"], "A1"); assert_eq!(row["backlinks"], "2"); } #[test] fn listing_sorts_by_date_desc_with_undated_last() { let documents = vec![ document("notes/a.md", "/notes/a/", "A", Some("2026-01-01"), &[]), document("notes/b.md", "/notes/b/", "B", Some("2026-02-01"), &[]), document("notes/c.md", "/notes/c/", "C", None, &[]), ]; let config = config_with(vec![collection( "notes", "notes", "/notes/", Order::DateDesc, )]); let site = build(&config, &documents).unwrap(); let items = match site.pages[0].values.get("items") { Some(Value::List(items)) => items, _ => panic!("items missing"), }; let titles: Vec = items .iter() .map(|item| match item { Value::Map(row) => row["title"].clone(), _ => String::new(), }) .collect(); assert_eq!(titles, vec!["B", "A", "C"]); } #[test] fn generates_tag_pages_and_index() { let documents = vec![ document("a.md", "/a/", "A", None, &["Wiki", "rust"]), document("b.md", "/b/", "B", None, &["wiki"]), document("c.md", "/c/", "C", None, &["ação"]), ]; let site = build(&config_with(Vec::new()), &documents).unwrap(); let routes: Vec<&str> = site.pages.iter().map(|page| page.route.as_str()).collect(); assert!(routes.contains(&"/tags/")); assert!(routes.contains(&"/tags/wiki/")); assert!(routes.contains(&"/tags/rust/")); assert!(routes.contains(&"/tags/ao/")); } #[test] fn slug_collisions_are_errors() { let documents = vec![ document("a.md", "/a/", "A", None, &["C++"]), document("b.md", "/b/", "B", None, &["C"]), ]; let error = build(&config_with(Vec::new()), &documents).unwrap_err(); assert!(error.contains("both become")); } #[test] fn generated_routes_cannot_collide_with_pages() { let documents = vec![document( "tags/wiki.md", "/tags/wiki/", "Wiki", None, &["wiki"], )]; let error = build(&config_with(Vec::new()), &documents).unwrap_err(); assert!(error.contains("already used by")); } #[test] fn root_collection_lists_all_pages() { let documents = vec![ document("index.md", "/", "Home", None, &[]), document("a.md", "/a/", "A", None, &[]), ]; let config = config_with(vec![collection("all", ".", "/all/", Order::Path)]); let site = build(&config, &documents).unwrap(); assert_eq!(titles(&site.pages[0]), vec!["A", "Home"]); } #[test] fn collection_route_cannot_equal_a_page_route() { let documents = vec![document("index.md", "/", "Home", None, &[])]; let config = config_with(vec![collection("all", ".", "/", Order::Path)]); let error = build(&config, &documents).unwrap_err(); assert!(error.contains("already used by")); } #[test] fn prefix_matches_whole_segments() { let documents = vec![ document("notes/a.md", "/notes/a/", "A", None, &[]), document("notes2/b.md", "/notes2/b/", "B", None, &[]), ]; let config = config_with(vec![collection("notes", "notes", "/notes/", Order::Path)]); let site = build(&config, &documents).unwrap(); assert_eq!(titles(&site.pages[0]), vec!["A"]); } #[test] fn listing_sorts_by_title() { let documents = vec![ document("n/b.md", "/n/b/", "Beta", None, &[]), document("n/a.md", "/n/a/", "alpha", None, &[]), ]; let config = config_with(vec![collection("n", "n", "/n/", Order::Title)]); let site = build(&config, &documents).unwrap(); assert_eq!(titles(&site.pages[0]), vec!["alpha", "Beta"]); } #[test] fn listing_sorts_by_date_asc() { let documents = vec![ document("n/a.md", "/n/a/", "A", Some("2026-02-01"), &[]), document("n/b.md", "/n/b/", "B", Some("2026-01-01"), &[]), document("n/c.md", "/n/c/", "C", None, &[]), ]; let config = config_with(vec![collection("n", "n", "/n/", Order::DateAsc)]); let site = build(&config, &documents).unwrap(); assert_eq!(titles(&site.pages[0]), vec!["B", "A", "C"]); } #[test] fn empty_collection_still_generates_a_listing() { let config = config_with(vec![collection("empty", "empty", "/empty/", Order::Path)]); let site = build(&config, &[]).unwrap(); assert_eq!(site.pages.len(), 1); assert_eq!(site.pages[0].route, "/empty/"); assert!(titles(&site.pages[0]).is_empty()); } #[test] fn collection_path_outside_content_is_an_error() { let mut broken = collection("x", "x", "/x/", Order::Path); broken.path = std::path::PathBuf::from("/elsewhere"); let error = build(&config_with(vec![broken]), &[]).unwrap_err(); assert!(error.contains("not inside the content directory")); } #[test] fn tags_group_case_insensitively_and_keep_the_first_label() { let documents = vec![ document("a.md", "/a/", "A", None, &["Wiki"]), document("b.md", "/b/", "B", None, &["wiki"]), ]; let site = build(&config_with(Vec::new()), &documents).unwrap(); let wiki = site .pages .iter() .find(|page| page.route == "/tags/wiki/") .unwrap(); assert_eq!(wiki.title, "Wiki"); assert_eq!(titles(wiki).len(), 2); } #[test] fn tag_index_rows_have_counts_and_links() { let documents = vec![ document("a.md", "/a/", "A", None, &["wiki"]), document("b.md", "/b/", "B", None, &["wiki", "rust"]), ]; let site = build(&config_with(Vec::new()), &documents).unwrap(); let index = site .pages .iter() .find(|page| page.route == "/tags/") .unwrap(); let rows: Vec> = match index.values.get("items") { Some(Value::List(items)) => items .iter() .map(|item| match item { Value::Map(row) => row.clone(), _ => panic!("expected a map"), }) .collect(), _ => panic!("items missing"), }; assert_eq!(rows[0]["tag"], "rust"); assert_eq!(rows[0]["count"], "1"); assert_eq!(rows[1]["tag"], "wiki"); assert_eq!(rows[1]["count"], "2"); } #[test] fn tags_without_ascii_letters_are_errors() { let documents = vec![document("a.md", "/a/", "A", None, &["日本語"])]; let error = build(&config_with(Vec::new()), &documents).unwrap_err(); assert!(error.contains("no letters or digits")); } #[test] fn link_targets_expose_tags() { let documents = vec![document("a.md", "/a/", "A", None, &["Wiki"])]; let site = build(&config_with(Vec::new()), &documents).unwrap(); assert!(site.link_targets().iter().any(|target| { target.route == "/tags/wiki/" && target .tag .as_ref() .is_some_and(|tag| tag.slug == "wiki" && tag.label == "Wiki") })); } #[test] fn collections_cannot_share_a_route() { let config = config_with(vec![ collection("a", "a", "/shared/", Order::Path), collection("b", "b", "/shared/", Order::Path), ]); let error = build(&config, &[]).unwrap_err(); assert!(error.contains("already used by")); } #[test] fn tag_routes_cannot_collide_with_collections() { let documents = vec![document("a.md", "/a/", "A", None, &["wiki"])]; let config = config_with(vec![collection( "tags-wiki", "x", "/tags/wiki/", Order::Path, )]); let error = build(&config, &documents).unwrap_err(); assert!(error.contains("already used by")); } #[test] fn tag_slugs_drop_accents_and_punctuation() { assert_eq!(tag_slug("ação"), "ao"); assert_eq!(tag_slug("C++"), "c"); assert_eq!(tag_slug(" hello_world "), "hello-world"); } }