aphid 0.1.1

A static site generator for blogs and wikis, with wiki-links across both.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
pub mod context;
pub mod theme;

pub use context::*;
pub use theme::Theme;

use std::collections::HashMap;

use rayon::prelude::*;
use serde::Serialize;
use tera::Context;

use crate::Error;
use crate::config::Config;
use crate::content::{PageAny, Site};
use crate::generated::{FaviconSet, Robots, Sitemap};
use crate::html::insert_before_closing_tag;
use crate::markdown::{MarkdownRenderer, Rendered};

/// In-memory representation of the rendered site.
pub struct RenderedSite {
    /// URL path -> rendered HTML (e.g. "/blog/hello/" -> "<html>...</html>")
    pub pages: HashMap<String, String>,
    /// Pre-rendered 404 page HTML.
    pub not_found_html: String,
    /// Files written at the site root (e.g. `favicon.ico`, `robots.txt`,
    /// `sitemap.xml`). Each entry is `(filename, bytes)`.
    pub root_files: Vec<(String, Vec<u8>)>,
}

impl RenderedSite {
    /// Load content from `config` and render every page against `theme`.
    ///
    /// If `fail_on_broken_links` is `true`, returns [`Error::BrokenWikiLinks`]
    /// when any wiki-link target is missing. When `false`, broken links are
    /// logged as warnings and rendered with a `class="wikilink broken"` span.
    pub fn build(
        config: &Config,
        theme: &Theme,
        fail_on_broken_links: bool,
    ) -> Result<Self, Error> {
        let favicon = config
            .favicon
            .as_ref()
            .map(|p| FaviconSet::generate(p, &config.title))
            .transpose()?;
        Self::build_with_favicon(config, theme, fail_on_broken_links, favicon)
    }

    /// Like [`build`](Self::build) but accepts a pre-built [`FaviconSet`].
    ///
    /// Serve-mode rebuilds pass the cached set from the initial render so
    /// the expensive image-processing step is not repeated on every file
    /// change.
    pub fn build_with_favicon(
        config: &Config,
        theme: &Theme,
        fail_on_broken_links: bool,
        favicon: Option<FaviconSet>,
    ) -> Result<Self, Error> {
        tracing::info!(source = %config.source_dir.display(), "loading content");
        let site = Site::load(config.clone())?;
        Renderer::new(theme).render_all(&site, config, fail_on_broken_links, favicon)
    }

    /// Look up rendered HTML for a URL path, normalising trailing slashes.
    pub fn lookup(&self, path: &str) -> Option<&str> {
        if path.ends_with('/') {
            self.pages.get(path).map(String::as_str)
        } else {
            self.pages.get(&format!("{path}/")).map(String::as_str)
        }
    }
}

struct RenderedPages {
    blog: Vec<Rendered>,
    wiki: Vec<Rendered>,
    pages: Vec<Rendered>,
    home: Option<Rendered>,
}

impl RenderedPages {
    fn iter_pages(&self) -> impl Iterator<Item = &Rendered> {
        self.blog
            .iter()
            .chain(self.wiki.iter())
            .chain(self.pages.iter())
    }
}

/// Pass-2 orchestrator: takes a [`Site`] and a [`Theme`] and produces a
/// fully-rendered [`RenderedSite`]. Internally runs the markdown pipeline
/// per page (in parallel via rayon), then per-page Tera template
/// rendering, then the index/tag/404 pages.
pub struct Renderer<'a> {
    theme: &'a Theme,
}

impl<'a> Renderer<'a> {
    pub fn new(theme: &'a Theme) -> Self {
        Self { theme }
    }

    /// Render the entire site: markdown pass, broken-link policy, template rendering.
    fn render_all(
        &self,
        site: &Site,
        config: &Config,
        fail_on_broken_links: bool,
        favicon: Option<FaviconSet>,
    ) -> Result<RenderedSite, Error> {
        tracing::info!("rendering markdown");
        let rendered = Self::render_markdown(site);
        Self::check_broken_links(&rendered, site, fail_on_broken_links)?;

        let site_ctx = SiteContext::from_config(&site.config, &site.pages);
        let wiki_categories = WikiCategory::from_site(site);
        let mut pages = self.render_content_pages(&rendered, site, &site_ctx, &wiki_categories)?;
        pages.extend(self.render_tag_pages(site, &site_ctx)?);
        pages.extend(self.render_index_pages(site, &rendered, &site_ctx, &wiki_categories)?);

        let mut not_found_html =
            self.render_template("404.html", &NotFoundContext { site: site_ctx })?;

        // ── Root files (favicon, robots.txt, sitemap.xml) ───────────────
        let mut root_files: Vec<(String, Vec<u8>)> = Vec::new();

        if let Some(set) = favicon {
            root_files.extend(set.files.clone());
            inject_into_head(&mut pages, &set.html_tags);
            inject_into_head_single(&mut not_found_html, &set.html_tags);
        }

        root_files.push((
            "robots.txt".into(),
            Robots::new(config.normalized_base_url()).into_bytes(),
        ));
        root_files.push(("sitemap.xml".into(), Sitemap::new(site).into_bytes()));

        Ok(RenderedSite {
            pages,
            not_found_html,
            root_files,
        })
    }

    fn render_markdown(site: &Site) -> RenderedPages {
        let md = MarkdownRenderer::new(site);
        // Page-body rendering preserves slice order, so blog/wiki/pages can
        // all render in parallel without disturbing page-to-render alignment.
        let (blog, wiki) = rayon::join(
            || Self::render_page_bodies(&site.blog, &md),
            || Self::render_page_bodies(&site.wiki, &md),
        );
        let pages = Self::render_page_bodies(&site.pages, &md);
        let home = site.home.as_ref().map(|page| md.render(&page.body));
        RenderedPages {
            blog,
            wiki,
            pages,
            home,
        }
    }

    fn render_page_bodies<F: Sync>(
        pages: &[crate::content::page::Page<F>],
        md: &MarkdownRenderer<'_>,
    ) -> Vec<Rendered> {
        pages.par_iter().map(|page| md.render(&page.body)).collect()
    }

    fn check_broken_links(rendered: &RenderedPages, site: &Site, fail: bool) -> Result<(), Error> {
        let all_broken = site
            .iter_pages()
            .zip(rendered.iter_pages())
            .flat_map(|(page, rendered_page)| {
                rendered_page
                    .broken_wiki_links
                    .iter()
                    .map(move |target| (page.slug().to_string(), target.clone()))
            })
            .chain(
                rendered
                    .home
                    .iter()
                    .flat_map(|r| r.broken_wiki_links.iter().cloned())
                    .map(|target| ("home.md".to_string(), target)),
            );

        if fail {
            let broken: Vec<(String, String)> = all_broken.collect();
            if !broken.is_empty() {
                return Err(Error::BrokenWikiLinks(broken));
            }
        } else {
            for (slug, target) in all_broken {
                tracing::warn!(page = slug, target, "broken wiki-link");
            }
        }
        Ok(())
    }

    fn render_content_pages(
        &self,
        rendered: &RenderedPages,
        site: &Site,
        site_ctx: &SiteContext,
        wiki_categories: &[WikiCategory],
    ) -> Result<HashMap<String, String>, Error> {
        let all_pages: Vec<(PageAny<'_>, &Rendered)> =
            site.iter_pages().zip(rendered.iter_pages()).collect();

        all_pages
            .into_par_iter()
            .map(|(page, md)| {
                let ctx = PageContext::from_page(&page, md, site, site_ctx, wiki_categories);
                let html = self.render_template(ctx.template_name(), &ctx)?;
                Ok((ctx.url, html))
            })
            .collect()
    }

    fn render_tag_pages(
        &self,
        site: &Site,
        site_ctx: &SiteContext,
    ) -> Result<HashMap<String, String>, Error> {
        let mut pages = HashMap::new();
        let mut all_tags: Vec<TagEntry> = Vec::new();

        for (tag, slugs) in &site.tag_index {
            let posts = PostEntry::from_pages(slugs.iter().filter_map(|slug| site.get(slug)));

            let tag_entry = TagEntry::new(tag, posts.len());
            let tag_slug = tag_entry.slug.clone();
            all_tags.push(tag_entry);

            let ctx = TagPageContext {
                site: site_ctx.clone(),
                tag: tag.clone(),
                tag_slug: tag_slug.clone(),
                posts,
            };
            let html = self.render_template("tag.html", &ctx)?;
            pages.insert(format!("/tags/{tag_slug}/"), html);
        }

        all_tags.sort_by(|a, b| a.name.cmp(&b.name));
        let ctx = TagsIndexContext {
            site: site_ctx.clone(),
            tags: all_tags,
        };
        let html = self.render_template("tags_index.html", &ctx)?;
        pages.insert("/tags/".into(), html);

        Ok(pages)
    }

    fn render_index_pages(
        &self,
        site: &Site,
        rendered: &RenderedPages,
        site_ctx: &SiteContext,
        wiki_categories: &[WikiCategory],
    ) -> Result<HashMap<String, String>, Error> {
        let mut pages = HashMap::new();

        let posts = PostEntry::from_pages(site.blog.iter().map(PageAny::Blog));

        let home_rendered = site.home.as_ref().and(rendered.home.as_ref());
        let home_content = home_rendered.map(HomeContent::from);
        let contains_mermaid = home_rendered.is_some_and(|r| r.contains_mermaid);
        let home_ctx = HomeContext {
            site: site_ctx.clone(),
            posts: posts.clone(),
            home: home_content,
            contains_mermaid,
        };
        pages.insert("/".into(), self.render_template("home.html", &home_ctx)?);

        let blog_ctx = BlogIndexContext {
            site: site_ctx.clone(),
            posts,
        };
        pages.insert(
            "/blog/".into(),
            self.render_template("blog_index.html", &blog_ctx)?,
        );

        let wiki_ctx = WikiIndexContext {
            site: site_ctx.clone(),
            categories: wiki_categories.to_vec(),
        };
        pages.insert(
            "/wiki/".into(),
            self.render_template("wiki_index.html", &wiki_ctx)?,
        );

        Ok(pages)
    }

    fn render_template<T: Serialize>(&self, template: &str, ctx: &T) -> Result<String, Error> {
        let tera_ctx = Context::from_serialize(ctx)?;
        let html = self.theme.tera.render(template, &tera_ctx)?;
        Ok(html)
    }
}

/// Inject `tags` before `</head>` in every page's HTML.
fn inject_into_head(pages: &mut HashMap<String, String>, tags: &str) {
    for html in pages.values_mut() {
        inject_into_head_single(html, tags);
    }
}

/// Inject `tags` before the first `</head>` in a single HTML string.
fn inject_into_head_single(html: &mut String, tags: &str) {
    insert_before_closing_tag(html, "</head>", tags);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::content::page::PageKind;

    #[test]
    fn page_context_selects_correct_template() {
        let site = SiteContext {
            site_title: "Test".into(),
            base_url: "http://localhost".into(),
            version: "0.0.0".into(),
            nav_pages: vec![],
            socials: vec![],
        };
        let ctx = PageContext {
            site: site.clone(),
            title: "Hello".into(),
            url: "/blog/hello/".into(),
            kind: PageKind::Blog,
            content: "<p>Hello</p>".into(),
            toc: vec![],
            backlinks: vec![],
            contains_mermaid: false,
            category: None,
            wiki_categories: vec![],
            author: Some("Alice".into()),
            image: None,
            description: None,
            created: Some("2026-01-01".into()),
            updated: None,
            tags: vec![TagRef {
                name: "rust".into(),
                slug: "rust".into(),
            }],
        };
        assert_eq!(ctx.template_name(), "blog_post.html");

        let wiki_ctx = PageContext {
            site,
            kind: PageKind::Wiki,
            ..ctx
        };
        assert_eq!(wiki_ctx.template_name(), "wiki_page.html");
    }

    #[test]
    fn render_page_with_inline_template() {
        let mut tera = tera::Tera::default();
        tera.add_raw_template(
            "blog_post.html",
            "<h1>{{ title }}</h1><div>{{ content | safe }}</div>",
        )
        .unwrap();

        // Build a Theme with the inline Tera (bypass from_dir)
        let theme = Theme {
            meta: theme::ThemeMeta {
                name: "test".into(),
                version: "0.1.0".into(),
                description: None,
            },
            tera,
            static_dir: None,
            embedded_static: vec![],
        };

        let renderer = Renderer::new(&theme);
        let ctx = PageContext {
            site: SiteContext {
                site_title: "Test Site".into(),
                base_url: "http://localhost".into(),
                version: "0.0.0".into(),
                nav_pages: vec![],
                socials: vec![],
            },
            title: "My Post".into(),
            url: "/blog/my-post/".into(),
            kind: PageKind::Blog,
            content: "<p>Body here</p>".into(),
            toc: vec![],
            backlinks: vec![],
            contains_mermaid: false,
            category: None,
            wiki_categories: vec![],
            author: Some("Alice".into()),
            image: None,
            description: None,
            created: Some("2026-01-01".into()),
            updated: None,
            tags: vec![],
        };

        let html = renderer.render_template(ctx.template_name(), &ctx).unwrap();
        assert!(html.contains("<h1>My Post</h1>"));
        assert!(html.contains("<p>Body here</p>"));
    }

    #[test]
    fn nav_entries_sorted_by_order_then_title() {
        use crate::content::PageFrontmatter;
        use crate::content::page::Page;
        use std::path::PathBuf;

        let pages = vec![
            Page {
                slug: "contact".into(),
                body: String::new(),
                path: PathBuf::from("content/pages/contact.md"),
                frontmatter: PageFrontmatter {
                    title: "Contact".into(),
                    order: Some(2),
                },
            },
            Page {
                slug: "about".into(),
                body: String::new(),
                path: PathBuf::from("content/pages/about.md"),
                frontmatter: PageFrontmatter {
                    title: "About".into(),
                    order: Some(1),
                },
            },
            Page {
                slug: "faq".into(),
                body: String::new(),
                path: PathBuf::from("content/pages/faq.md"),
                frontmatter: PageFrontmatter {
                    title: "FAQ".into(),
                    order: None,
                },
            },
        ];

        let nav = NavEntry::from_pages(&pages);
        assert_eq!(nav.len(), 3);
        assert_eq!(nav[0].title, "About");
        assert_eq!(nav[0].url, "/about/");
        assert_eq!(nav[1].title, "Contact");
        assert_eq!(nav[1].url, "/contact/");
        assert_eq!(nav[2].title, "FAQ"); // order=None → MAX → last
    }
}