Skip to main content

cascivo_html/
render.rs

1//! Document assembly: parse → brand → emit → one self-contained HTML string.
2
3use std::collections::BTreeSet;
4
5use crate::ast::{Directive, Doc};
6use crate::brand::{Brand, document_brand};
7use crate::css_gen::{BASE_CSS, COMPONENT_CSS, THEMES};
8use crate::diag::Diagnostic;
9use crate::emit::emit;
10use crate::html::esc;
11use crate::parse::parse;
12
13/// Resolves `@brand-file` paths. The library itself never touches the filesystem.
14pub type BrandResolver = &'static dyn Fn(&str) -> Result<String, String>;
15
16/// Loads the bytes of an image/SVG source (a path or URL). Never called for `data:` URIs.
17pub type AssetResolver = &'static dyn Fn(&str) -> Result<Vec<u8>, String>;
18
19#[derive(Clone, Default)]
20pub struct Options {
21    pub brand: Option<Brand>,
22    pub brand_resolver: Option<BrandResolver>,
23    pub minify_html: bool,
24    /// Pre-supplied bytes keyed by the exact `src` written in the `.cv`; looked up first, so a
25    /// web server can pass uploads without a `'static` resolver.
26    pub assets: Vec<(String, Vec<u8>)>,
27    pub asset_resolver: Option<AssetResolver>,
28    /// Also send `http(s)://` sources to `asset_resolver`; otherwise they stay plain references.
29    pub embed_urls: bool,
30    /// Largest embeddable asset in bytes (default 2 MiB).
31    pub max_asset_bytes: Option<usize>,
32}
33
34/// Per-document emit state. Ids come from a counter so output is deterministic.
35#[derive(Default)]
36pub struct Cx<'a> {
37    next_id: u32,
38    pub(crate) opts: Option<&'a Options>,
39    pub(crate) diags: Vec<Diagnostic>,
40    pub used: BTreeSet<&'static str>,
41    pub scripts: BTreeSet<&'static str>,
42}
43
44impl Cx<'_> {
45    /// `cv-1`, `cv-2`, …
46    pub fn id(&mut self) -> String {
47        self.next_id += 1;
48        format!("cv-{}", self.next_id)
49    }
50}
51
52/// CSS that only some emitters need beyond the per-component module (inside `@layer cascivo.component`).
53// Static output has no load handler, so the image must not stay hidden behind its placeholder.
54const EXTRA_CSS: &[(&str, &str)] = &[
55    ("image", include_str!("../assets/extra/image.css")),
56    ("tabs", include_str!("../assets/extra/tabs.css")),
57];
58
59/// Inline scripts, keyed by the name emitters put in `Cx::scripts`.
60const SCRIPTS: &[(&str, &str)] = &[("table-sort", include_str!("../assets/extra/table-sort.js"))];
61
62/// Page shell: inline padding and a vertical rhythm from the brand's `gap` (default space-4).
63/// Mobile-first, no max-width: the document fills the viewport like a dashboard.
64const DOC_CSS: &str = "@layer cascivo.component{.cv-doc{display:flex;flex-direction:column;gap:var(--cascivo-gap-default,var(--cascivo-space-4));padding:var(--cascivo-space-4);min-inline-size:0}@media (min-width:40rem){.cv-doc{padding:var(--cascivo-space-6)}}@media (min-width:64rem){.cv-doc{padding:var(--cascivo-space-8)}}}";
65
66fn emit_body(doc: &Doc, cx: &mut Cx<'_>) -> String {
67    let mut body = String::new();
68    for node in &doc.nodes {
69        emit(node, cx, &mut body);
70    }
71    body
72}
73
74/// Base, theme, page-shell and per-component CSS for the given used units: what [`render`]
75/// inlines, so a multi-page site can ship it once as a shared stylesheet. Unknown themes fall
76/// back to the base tokens only.
77pub fn stylesheet(theme: &str, used: &BTreeSet<&'static str>) -> String {
78    let mut css = String::from(BASE_CSS);
79    if let Some((_, c)) = THEMES.iter().find(|(n, _)| *n == theme) {
80        css.push_str(c);
81    }
82    css.push_str(DOC_CSS);
83    for (unit, c) in COMPONENT_CSS.iter().chain(EXTRA_CSS) {
84        if used.contains(unit) {
85            css.push_str(c);
86        }
87    }
88    css
89}
90
91/// Inline script source an emitter asked for via [`Fragment::scripts`].
92pub fn script(name: &str) -> Option<&'static str> {
93    SCRIPTS.iter().find(|(n, _)| *n == name).map(|(_, js)| *js)
94}
95
96/// Body markup plus what it needs from [`stylesheet`] and [`script`].
97#[derive(Debug, Clone, Default)]
98pub struct Fragment {
99    pub html: String,
100    pub used: BTreeSet<&'static str>,
101    pub scripts: BTreeSet<&'static str>,
102}
103
104/// Like [`render_fragment`], but with asset options and the used CSS units and scripts, so a
105/// host (cascivo-web) can embed several fragments in its own page shell.
106pub fn render_parts(src: &str, opts: &Options) -> Result<Fragment, Vec<Diagnostic>> {
107    let doc = parse(src)?;
108    let mut cx = Cx {
109        opts: Some(opts),
110        ..Cx::default()
111    };
112    let html = emit_body(&doc, &mut cx);
113    if cx.diags.is_empty() {
114        Ok(Fragment {
115            html,
116            used: cx.used,
117            scripts: cx.scripts,
118        })
119    } else {
120        Err(cx.diags)
121    }
122}
123
124/// Body markup only (no document shell); used by conformance snapshots.
125pub fn render_fragment(src: &str) -> Result<String, Vec<Diagnostic>> {
126    let doc = parse(src)?;
127    let mut cx = Cx::default();
128    let body = emit_body(&doc, &mut cx);
129    if cx.diags.is_empty() {
130        Ok(body)
131    } else {
132        Err(cx.diags)
133    }
134}
135
136pub fn render(src: &str, opts: &Options) -> Result<String, Vec<Diagnostic>> {
137    let doc = parse(src)?;
138    let (theme, brand_css) = document_brand(&doc, opts)?;
139    let mut cx = Cx {
140        opts: Some(opts),
141        ..Cx::default()
142    };
143    let body = emit_body(&doc, &mut cx);
144    if !cx.diags.is_empty() {
145        return Err(cx.diags);
146    }
147
148    let mut title = "";
149    let mut lang = "en";
150    for d in &doc.directives {
151        match d {
152            Directive::Title(t) => title = t,
153            Directive::Lang(l) => lang = l,
154            _ => {}
155        }
156    }
157    let theme = theme.as_deref().unwrap_or("light");
158    let mut css = stylesheet(theme, &cx.used);
159    // Brand CSS overrides theme tokens, so it goes after them but before the component modules.
160    let at = BASE_CSS.len()
161        + THEMES
162            .iter()
163            .find(|(n, _)| *n == theme)
164            .map_or(0, |(_, c)| c.len());
165    css.insert_str(at, &brand_css);
166
167    let nl = if opts.minify_html { "" } else { "\n" };
168    let mut out = String::with_capacity(css.len() + body.len() + 256);
169    out.push_str("<!doctype html>");
170    out.push_str(nl);
171    out.push_str("<html lang=\"");
172    esc(&mut out, lang);
173    out.push_str("\" data-theme=\"");
174    esc(&mut out, theme);
175    out.push_str("\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>");
176    esc(&mut out, title);
177    out.push_str("</title><style>");
178    out.push_str(&css);
179    out.push_str("</style></head>");
180    out.push_str(nl);
181    out.push_str("<body><main class=\"cv-doc\">");
182    out.push_str(&body);
183    out.push_str("</main></body>");
184    for (name, js) in SCRIPTS {
185        if cx.scripts.contains(name) {
186            out.push_str("<script>");
187            out.push_str(js);
188            out.push_str("</script>");
189        }
190    }
191    out.push_str("</html>");
192    out.push_str(nl);
193    Ok(out)
194}
195
196/// A resolved `src`: bytes to embed, or a string to use as-is.
197pub(crate) enum Asset {
198    Bytes {
199        mime: &'static str,
200        bytes: Vec<u8>,
201    },
202    /// A `data:` URI or an `http(s)` URL left as a reference.
203    Passthrough(String),
204}
205
206impl Cx<'_> {
207    pub(crate) fn error(&mut self, node: &crate::ast::Node, msg: impl Into<String>) {
208        self.diags.push(Diagnostic::new(node.line, node.col, msg));
209    }
210
211    /// Turns a `src` into bytes or a passthrough string; on failure records a diagnostic.
212    /// `allow_ref` lets an unfetched `http(s)` URL stay a plain reference (images only).
213    pub(crate) fn load_asset(
214        &mut self,
215        node: &crate::ast::Node,
216        src: &str,
217        allow_ref: bool,
218    ) -> Option<Asset> {
219        let src = src.trim();
220        let opts = self.opts;
221        // Fragment mode (no Options) is the conformance path: sources stay untouched references.
222        if opts.is_none() && allow_ref {
223            return Some(Asset::Passthrough(src.to_string()));
224        }
225        let lower = src.to_ascii_lowercase();
226        if lower.starts_with("data:") {
227            // Only inert image types; `data:image/svg+xml` is safe in <img>, never inlined.
228            let ok = ["png", "jpeg", "gif", "webp", "avif", "svg+xml", "x-icon"]
229                .iter()
230                .any(|m| {
231                    lower.starts_with(&format!("data:image/{m};"))
232                        || lower.starts_with(&format!("data:image/{m},"))
233                });
234            if ok && allow_ref {
235                return Some(Asset::Passthrough(src.to_string()));
236            }
237            self.error(node, "data: URIs are only accepted for raster/svg images in `image`; give `svg` a file path or inline markup");
238            return None;
239        }
240        let is_url = lower.starts_with("http://") || lower.starts_with("https://");
241        let found = opts.and_then(|o| {
242            o.assets
243                .iter()
244                .find(|(k, _)| k == src)
245                .map(|(_, b)| b.clone())
246        });
247        let bytes = match found {
248            Some(b) => b,
249            None => {
250                let resolver = opts
251                    .and_then(|o| o.asset_resolver)
252                    .filter(|_| !is_url || opts.is_some_and(|o| o.embed_urls));
253                match resolver {
254                    Some(r) => match r(src) {
255                        Ok(b) => b,
256                        Err(e) => {
257                            self.error(node, format!("cannot load '{src}': {e}"));
258                            return None;
259                        }
260                    },
261                    None if is_url && allow_ref => {
262                        return Some(Asset::Passthrough(src.to_string()));
263                    }
264                    None if is_url => {
265                        self.error(node, format!("cannot inline '{src}': URLs are fetched only with the CLI's --fetch (or Options::assets); give `svg` a file path or inline markup"));
266                        return None;
267                    }
268                    None => {
269                        self.error(node, format!("cannot load '{src}': no asset source configured; use the cascivo-html CLI (paths relative to the .cv file, more roots via --assets) or pass the bytes in Options::assets"));
270                        return None;
271                    }
272                }
273            }
274        };
275        let max = opts
276            .and_then(|o| o.max_asset_bytes)
277            .unwrap_or(crate::asset::DEFAULT_MAX_ASSET_BYTES);
278        if bytes.len() > max {
279            self.error(node, format!("'{src}' is {} bytes, over the {max}-byte embed limit (raise it with --max-asset or Options::max_asset_bytes)", bytes.len()));
280            return None;
281        }
282        let Some(mime) = crate::asset::sniff_mime(&bytes, src) else {
283            self.error(
284                node,
285                format!(
286                    "'{src}': unknown image type (expected png, jpeg, gif, webp, avif, svg or ico)"
287                ),
288            );
289            return None;
290        };
291        Some(Asset::Bytes { mime, bytes })
292    }
293}