Skip to main content

reflex/pulse/render/
bundle.rs

1//! Write the page bundle the site template builds from.
2//!
3//! ```text
4//! <site>/pulse.config.json         title, base, tabs, per-tab sidebar trees, build knobs
5//! <site>/bundle/index.json         [{id, tab, hash}] — one row per page except the home
6//! <site>/bundle/pages/<id>.json    {title, description, template, headings, html}
7//! <site>/bundle/pages/index.json   the home page (route `/`)
8//! <site>/src/styles/pulse-highlight.css
9//! ```
10//! Page ids are routes without slashes (`docs/changelog`, `internals`). Files are
11//! rewritten only when their bytes change, so Astro's incremental build and the
12//! content hashes in `index.json` stay stable.
13
14use super::html::{Heading, Renderer, highlight_css};
15use super::project::ProjectWriter;
16use crate::pulse::model::{NavNode, PageKind, Site, TabId};
17use anyhow::Result;
18use rayon::prelude::*;
19use serde::Serialize;
20use serde_json::json;
21
22/// Where the site is served from.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct BaseUrl {
25    /// `https://host` when an absolute URL was given.
26    pub site: Option<String>,
27    /// `/` or `/sub/`.
28    pub base: String,
29}
30
31impl BaseUrl {
32    /// `https://host/sub` → site `https://host`, base `/sub/`; `/sub` → base `/sub/`.
33    pub fn parse(s: &str) -> Self {
34        let s = s.trim();
35        let (site, path) = match s.split_once("://") {
36            Some((scheme, rest)) => {
37                let (host, path) = rest.split_once('/').unwrap_or((rest, ""));
38                (Some(format!("{scheme}://{host}")), path.to_string())
39            }
40            None => (None, s.to_string()),
41        };
42        let trimmed = path.trim_matches('/');
43        let base = if trimmed.is_empty() {
44            "/".to_string()
45        } else {
46            format!("/{trimmed}/")
47        };
48        Self { site, base }
49    }
50
51    /// The base without its trailing slash (`""` for the root).
52    pub fn prefix(&self) -> &str {
53        self.base.trim_end_matches('/')
54    }
55}
56
57#[derive(Serialize)]
58struct PageJson<'a> {
59    title: &'a str,
60    #[serde(skip_serializing_if = "Option::is_none")]
61    description: Option<&'a str>,
62    template: &'a str,
63    badges: &'a [String],
64    headings: Vec<Heading>,
65    html: String,
66    mermaid: bool,
67}
68
69fn page_id(route: &str) -> String {
70    let t = route.trim_matches('/');
71    if t.is_empty() {
72        "index".into()
73    } else {
74        t.into()
75    }
76}
77
78fn tab_key(tab: TabId) -> &'static str {
79    match tab {
80        TabId::Docs => "docs",
81        TabId::Internals => "internals",
82    }
83}
84
85fn sidebar(site: &Site, nodes: &[NavNode]) -> Vec<serde_json::Value> {
86    nodes
87        .iter()
88        .filter_map(|n| match n {
89            NavNode::Page { page } => {
90                let p = site.pages.get(page)?;
91                Some(json!({ "label": p.title, "slug": p.route.trim_matches('/') }))
92            }
93            NavNode::Group {
94                label,
95                collapsed,
96                children,
97            } => Some(json!({
98                "label": label,
99                "collapsed": collapsed,
100                "items": sidebar(site, children),
101            })),
102        })
103        .collect()
104}
105
106/// Summary of one bundle write.
107#[derive(Debug, Default, Clone, Copy)]
108pub struct BundleStats {
109    pub pages: usize,
110    pub written: usize,
111    pub unchanged: usize,
112    pub removed: usize,
113}
114
115/// Render every page and write the bundle into `site_dir`.
116pub fn write_bundle(
117    site: &Site,
118    site_dir: &std::path::Path,
119    base: &BaseUrl,
120) -> Result<BundleStats> {
121    let renderer = Renderer::new(site, &base.base);
122    let pages: Vec<_> = site.pages.values().collect();
123    let rendered: Vec<(String, TabId, Vec<u8>)> = pages
124        .par_iter()
125        .map(|p| {
126            let r = renderer.render_page(p);
127            let template = if matches!(p.kind, PageKind::Landing) {
128                "splash"
129            } else {
130                "doc"
131            };
132            let json = PageJson {
133                title: &p.title,
134                description: p.description.as_deref(),
135                template,
136                badges: &p.badges,
137                headings: r.headings,
138                html: r.html,
139                mermaid: r.has_mermaid,
140            };
141            let bytes = serde_json::to_vec(&json).expect("page JSON serializes");
142            (page_id(&p.route), p.tab, bytes)
143        })
144        .collect();
145
146    let mut w = ProjectWriter::open(site_dir)?;
147    let mut index = Vec::new();
148    for (id, tab, bytes) in &rendered {
149        w.put(&format!("bundle/pages/{id}.json"), bytes)?;
150        if id != "index" {
151            let hash = blake3::hash(bytes).to_hex()[..16].to_string();
152            index.push(json!({ "id": id, "tab": tab_key(*tab), "hash": hash }));
153        }
154    }
155    w.put("bundle/index.json", &serde_json::to_vec(&index)?)?;
156
157    let tabs: Vec<serde_json::Value> = site
158        .tabs
159        .iter()
160        .map(|t| {
161            let landing = site.pages.get(&t.landing);
162            json!({
163                "id": tab_key(t.id),
164                "label": t.label,
165                "prefix": t.id.prefix(),
166                "href": landing.map(|p| p.route.clone()).unwrap_or_else(|| t.id.prefix().to_string()),
167            })
168        })
169        .collect();
170    let mut sidebars = serde_json::Map::new();
171    for t in &site.tabs {
172        let mut nodes = Vec::new();
173        if let Some(l) = site.pages.get(&t.landing) {
174            let label = if t.id == TabId::Docs {
175                "Overview".to_string()
176            } else {
177                l.title.clone()
178            };
179            nodes.push(json!({ "label": label, "slug": l.route.trim_matches('/') }));
180        }
181        nodes.extend(sidebar(site, &t.nav));
182        sidebars.insert(tab_key(t.id).into(), serde_json::Value::Array(nodes));
183    }
184    let config = json!({
185        "title": site.meta.title,
186        "description": site.meta.description,
187        "site": base.site,
188        "base": base.base,
189        "tabs": tabs,
190        "sidebar": sidebars,
191        "sidebarFullTreeMax": 800,
192        "build": { "pageSource": "fs", "incremental": true },
193        "repo": site.meta.repo.as_ref().map(|r| r.web_url.clone()),
194        "generator": site.meta.generator,
195    });
196    // Astro validates types: an absent key is fine, `null` is not.
197    let mut config = config;
198    if let Some(obj) = config.as_object_mut() {
199        obj.retain(|_, v| !v.is_null());
200    }
201    w.put("pulse.config.json", &serde_json::to_vec_pretty(&config)?)?;
202    w.put("src/styles/pulse-highlight.css", highlight_css().as_bytes())?;
203
204    let s = w.finish("bundle/")?;
205    Ok(BundleStats {
206        pages: rendered.len(),
207        written: s.written,
208        unchanged: s.unchanged,
209        removed: s.removed,
210    })
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn base_urls() {
219        assert_eq!(
220            BaseUrl::parse("/"),
221            BaseUrl {
222                site: None,
223                base: "/".into()
224            }
225        );
226        assert_eq!(
227            BaseUrl::parse("/reflex"),
228            BaseUrl {
229                site: None,
230                base: "/reflex/".into()
231            }
232        );
233        assert_eq!(
234            BaseUrl::parse("https://pulse.rfx-search.dev"),
235            BaseUrl {
236                site: Some("https://pulse.rfx-search.dev".into()),
237                base: "/".into()
238            }
239        );
240        assert_eq!(
241            BaseUrl::parse("https://x.github.io/repo/"),
242            BaseUrl {
243                site: Some("https://x.github.io".into()),
244                base: "/repo/".into()
245            }
246        );
247        assert_eq!(BaseUrl::parse("/reflex/").prefix(), "/reflex");
248        assert_eq!(BaseUrl::parse("/").prefix(), "");
249    }
250
251    #[test]
252    fn page_ids() {
253        assert_eq!(page_id("/"), "index");
254        assert_eq!(page_id("/internals/"), "internals");
255        assert_eq!(page_id("/docs/reference/x/"), "docs/reference/x");
256    }
257}