Skip to main content

next_rust_view/
metadata.rs

1//! Document metadata (`<head>` contents).
2//!
3//! Layouts and pages each return a [`Metadata`]; the framework merges them
4//! from the root layout down to the page with [`Metadata::merge`]: every
5//! field set by a child overrides the parent's value, and a parent's
6//! `title_template` (e.g. `"%s | Acme"`) is applied to titles defined *below*
7//! it.
8
9use crate::escape::{escape_attr, escape_text};
10
11#[derive(Debug, Clone, Default, PartialEq, Eq)]
12pub struct Metadata {
13    pub title: Option<String>,
14    /// Applied to descendant titles; `%s` is replaced by the child title.
15    pub title_template: Option<String>,
16    /// When true, this title ignores ancestor templates.
17    pub title_absolute: bool,
18    pub description: Option<String>,
19    pub keywords: Option<Vec<String>>,
20    pub authors: Option<Vec<String>>,
21    pub canonical: Option<String>,
22    pub robots: Option<String>,
23    pub viewport: Option<String>,
24    pub theme_color: Option<String>,
25    pub color_scheme: Option<String>,
26    pub manifest: Option<String>,
27    pub icons: Option<Vec<Icon>>,
28    pub open_graph: Option<OpenGraph>,
29    pub twitter: Option<Twitter>,
30    /// `hreflang` alternates: (language, url).
31    pub alternates: Option<Vec<(String, String)>>,
32    /// Extra `<meta name=.. content=..>` entries.
33    pub other: Vec<(String, String)>,
34    /// External stylesheets (`<link rel="stylesheet">`).
35    pub stylesheets: Vec<String>,
36    /// Preloaded resources (fonts, images).
37    pub preloads: Vec<Preload>,
38}
39
40#[derive(Debug, Clone, Default, PartialEq, Eq)]
41pub struct Icon {
42    pub rel: String,
43    pub href: String,
44    pub sizes: Option<String>,
45    pub mime: Option<String>,
46}
47
48#[derive(Debug, Clone, Default, PartialEq, Eq)]
49pub struct OpenGraph {
50    pub title: Option<String>,
51    pub description: Option<String>,
52    pub url: Option<String>,
53    pub site_name: Option<String>,
54    pub kind: Option<String>,
55    pub locale: Option<String>,
56    pub images: Vec<OgImage>,
57}
58
59#[derive(Debug, Clone, Default, PartialEq, Eq)]
60pub struct OgImage {
61    pub url: String,
62    pub width: Option<u32>,
63    pub height: Option<u32>,
64    pub alt: Option<String>,
65}
66
67#[derive(Debug, Clone, Default, PartialEq, Eq)]
68pub struct Twitter {
69    pub card: Option<String>,
70    pub site: Option<String>,
71    pub creator: Option<String>,
72    pub title: Option<String>,
73    pub description: Option<String>,
74    pub images: Vec<String>,
75}
76
77#[derive(Debug, Clone, Default, PartialEq, Eq)]
78pub struct Preload {
79    pub href: String,
80    /// `font`, `image`, `style`, `script`, `fetch`.
81    pub as_: String,
82    pub mime: Option<String>,
83    pub crossorigin: bool,
84}
85
86macro_rules! setters {
87    ($($name:ident),*) => {$(
88        pub fn $name(mut self, v: impl Into<String>) -> Self {
89            self.$name = Some(v.into());
90            self
91        }
92    )*};
93}
94
95impl Metadata {
96    pub fn new() -> Self {
97        Self::default()
98    }
99
100    setters!(title, title_template, description, canonical, robots, viewport, theme_color, color_scheme, manifest);
101
102    /// A title that ignores ancestor templates.
103    pub fn absolute_title(mut self, v: impl Into<String>) -> Self {
104        self.title = Some(v.into());
105        self.title_absolute = true;
106        self
107    }
108
109    pub fn keywords<I, S>(mut self, v: I) -> Self
110    where
111        I: IntoIterator<Item = S>,
112        S: Into<String>,
113    {
114        self.keywords = Some(v.into_iter().map(Into::into).collect());
115        self
116    }
117
118    pub fn authors<I, S>(mut self, v: I) -> Self
119    where
120        I: IntoIterator<Item = S>,
121        S: Into<String>,
122    {
123        self.authors = Some(v.into_iter().map(Into::into).collect());
124        self
125    }
126
127    pub fn icon(mut self, href: impl Into<String>) -> Self {
128        self.icons.get_or_insert_with(Vec::new).push(Icon {
129            rel: "icon".into(),
130            href: href.into(),
131            sizes: None,
132            mime: None,
133        });
134        self
135    }
136
137    pub fn apple_touch_icon(mut self, href: impl Into<String>) -> Self {
138        self.icons.get_or_insert_with(Vec::new).push(Icon {
139            rel: "apple-touch-icon".into(),
140            href: href.into(),
141            sizes: None,
142            mime: None,
143        });
144        self
145    }
146
147    pub fn open_graph(mut self, og: OpenGraph) -> Self {
148        self.open_graph = Some(og);
149        self
150    }
151
152    pub fn twitter(mut self, tw: Twitter) -> Self {
153        self.twitter = Some(tw);
154        self
155    }
156
157    pub fn alternate(mut self, lang: impl Into<String>, href: impl Into<String>) -> Self {
158        self.alternates.get_or_insert_with(Vec::new).push((lang.into(), href.into()));
159        self
160    }
161
162    pub fn meta(mut self, name: impl Into<String>, content: impl Into<String>) -> Self {
163        self.other.push((name.into(), content.into()));
164        self
165    }
166
167    pub fn stylesheet(mut self, href: impl Into<String>) -> Self {
168        self.stylesheets.push(href.into());
169        self
170    }
171
172    /// Preload a font file (adds `crossorigin`, required for fonts).
173    pub fn preload_font(mut self, href: impl Into<String>) -> Self {
174        let href = href.into();
175        let mime = crate_mime(&href);
176        self.preloads.push(Preload { href, as_: "font".into(), mime, crossorigin: true });
177        self
178    }
179
180    pub fn preload_image(mut self, href: impl Into<String>) -> Self {
181        self.preloads.push(Preload { href: href.into(), as_: "image".into(), mime: None, crossorigin: false });
182        self
183    }
184
185    /// Merge `child` into `self` (child wins).
186    pub fn merge(mut self, child: Metadata) -> Metadata {
187        if let Some(t) = child.title {
188            self.title = Some(match (&self.title_template, child.title_absolute) {
189                (Some(tpl), false) => tpl.replace("%s", &t),
190                _ => t,
191            });
192        }
193        macro_rules! take {
194            ($($f:ident),*) => {$( if child.$f.is_some() { self.$f = child.$f; } )*};
195        }
196        take!(
197            title_template,
198            description,
199            keywords,
200            authors,
201            canonical,
202            robots,
203            viewport,
204            theme_color,
205            color_scheme,
206            manifest,
207            icons,
208            open_graph,
209            twitter,
210            alternates
211        );
212        for (k, v) in child.other {
213            if let Some(slot) = self.other.iter_mut().find(|(n, _)| *n == k) {
214                slot.1 = v;
215            } else {
216                self.other.push((k, v));
217            }
218        }
219        for s in child.stylesheets {
220            if !self.stylesheets.contains(&s) {
221                self.stylesheets.push(s);
222            }
223        }
224        for p in child.preloads {
225            if !self.preloads.contains(&p) {
226                self.preloads.push(p);
227            }
228        }
229        self
230    }
231
232    /// Render `<head>` contents.
233    pub fn render_head(&self) -> String {
234        let mut h = String::with_capacity(512);
235        h.push_str("<meta charset=\"utf-8\">");
236        let viewport = self.viewport.as_deref().unwrap_or("width=device-width, initial-scale=1");
237        meta_name(&mut h, "viewport", viewport);
238        if let Some(t) = &self.title {
239            h.push_str("<title>");
240            h.push_str(&escape_text(t));
241            h.push_str("</title>");
242        }
243        if let Some(d) = &self.description {
244            meta_name(&mut h, "description", d);
245        }
246        if let Some(k) = &self.keywords {
247            meta_name(&mut h, "keywords", &k.join(", "));
248        }
249        if let Some(a) = &self.authors {
250            for author in a {
251                meta_name(&mut h, "author", author);
252            }
253        }
254        if let Some(r) = &self.robots {
255            meta_name(&mut h, "robots", r);
256        }
257        if let Some(c) = &self.theme_color {
258            meta_name(&mut h, "theme-color", c);
259        }
260        if let Some(c) = &self.color_scheme {
261            meta_name(&mut h, "color-scheme", c);
262        }
263        if let Some(c) = &self.canonical {
264            link(&mut h, "canonical", c, &[]);
265        }
266        if let Some(alts) = &self.alternates {
267            for (lang, href) in alts {
268                link(&mut h, "alternate", href, &[("hreflang", lang)]);
269            }
270        }
271        if let Some(m) = &self.manifest {
272            link(&mut h, "manifest", m, &[]);
273        }
274        if let Some(icons) = &self.icons {
275            for i in icons {
276                let mut extra = Vec::new();
277                if let Some(s) = &i.sizes {
278                    extra.push(("sizes", s.as_str()));
279                }
280                if let Some(t) = &i.mime {
281                    extra.push(("type", t.as_str()));
282                }
283                link(&mut h, &i.rel, &i.href, &extra);
284            }
285        }
286        if let Some(og) = &self.open_graph {
287            let title = og.title.as_ref().or(self.title.as_ref());
288            let desc = og.description.as_ref().or(self.description.as_ref());
289            for (p, v) in [
290                ("og:title", title),
291                ("og:description", desc),
292                ("og:url", og.url.as_ref()),
293                ("og:site_name", og.site_name.as_ref()),
294                ("og:type", og.kind.as_ref()),
295                ("og:locale", og.locale.as_ref()),
296            ] {
297                if let Some(v) = v {
298                    meta_property(&mut h, p, v);
299                }
300            }
301            for img in &og.images {
302                meta_property(&mut h, "og:image", &img.url);
303                if let Some(w) = img.width {
304                    meta_property(&mut h, "og:image:width", &w.to_string());
305                }
306                if let Some(hh) = img.height {
307                    meta_property(&mut h, "og:image:height", &hh.to_string());
308                }
309                if let Some(a) = &img.alt {
310                    meta_property(&mut h, "og:image:alt", a);
311                }
312            }
313        }
314        if let Some(tw) = &self.twitter {
315            for (n, v) in [
316                ("twitter:card", tw.card.as_ref()),
317                ("twitter:site", tw.site.as_ref()),
318                ("twitter:creator", tw.creator.as_ref()),
319                ("twitter:title", tw.title.as_ref().or(self.title.as_ref())),
320                ("twitter:description", tw.description.as_ref().or(self.description.as_ref())),
321            ] {
322                if let Some(v) = v {
323                    meta_name(&mut h, n, v);
324                }
325            }
326            for img in &tw.images {
327                meta_name(&mut h, "twitter:image", img);
328            }
329        }
330        for (n, v) in &self.other {
331            meta_name(&mut h, n, v);
332        }
333        for p in &self.preloads {
334            h.push_str(&format!(
335                "<link rel=\"preload\" href=\"{}\" as=\"{}\"",
336                escape_attr(&p.href),
337                escape_attr(&p.as_)
338            ));
339            if let Some(m) = &p.mime {
340                h.push_str(&format!(" type=\"{}\"", escape_attr(m)));
341            }
342            if p.crossorigin {
343                h.push_str(" crossorigin");
344            }
345            h.push('>');
346        }
347        for s in &self.stylesheets {
348            link(&mut h, "stylesheet", s, &[]);
349        }
350        h
351    }
352}
353
354fn crate_mime(href: &str) -> Option<String> {
355    let ext = href.rsplit('.').next()?.to_ascii_lowercase();
356    Some(
357        match ext.as_str() {
358            "woff2" => "font/woff2",
359            "woff" => "font/woff",
360            "ttf" => "font/ttf",
361            "otf" => "font/otf",
362            _ => return None,
363        }
364        .into(),
365    )
366}
367
368fn meta_name(h: &mut String, name: &str, content: &str) {
369    h.push_str(&format!("<meta name=\"{}\" content=\"{}\">", escape_attr(name), escape_attr(content)));
370}
371
372fn meta_property(h: &mut String, prop: &str, content: &str) {
373    h.push_str(&format!("<meta property=\"{}\" content=\"{}\">", escape_attr(prop), escape_attr(content)));
374}
375
376fn link(h: &mut String, rel: &str, href: &str, extra: &[(&str, &str)]) {
377    let href = if crate::escape::is_safe_url(href) { href } else { "#" };
378    h.push_str(&format!("<link rel=\"{}\" href=\"{}\"", escape_attr(rel), escape_attr(href)));
379    for (k, v) in extra {
380        h.push_str(&format!(" {k}=\"{}\"", escape_attr(v)));
381    }
382    h.push('>');
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388
389    #[test]
390    fn merges_with_templates() {
391        let root = Metadata::new().title("Acme").title_template("%s | Acme").description("root");
392        let blog = Metadata::new().title("Blog").title_template("%s – Blog | Acme");
393        let post = Metadata::new().title("Hello").keywords(["rust"]);
394        let merged = Metadata::default().merge(root.clone()).merge(blog).merge(post);
395        assert_eq!(merged.title.as_deref(), Some("Hello – Blog | Acme"));
396        assert_eq!(merged.description.as_deref(), Some("root"));
397        let merged = Metadata::default().merge(root.clone());
398        assert_eq!(merged.title.as_deref(), Some("Acme"), "template does not apply to the same segment");
399        let merged = Metadata::default().merge(root).merge(Metadata::new().absolute_title("Standalone"));
400        assert_eq!(merged.title.as_deref(), Some("Standalone"));
401    }
402
403    #[test]
404    fn renders_escaped_head() {
405        let m = Metadata::new()
406            .title("<script>")
407            .description("a \"quote\"")
408            .canonical("javascript:alert(1)")
409            .open_graph(OpenGraph {
410                images: vec![OgImage { url: "/og.png".into(), width: Some(1200), ..Default::default() }],
411                ..Default::default()
412            })
413            .preload_font("/fonts/inter.woff2");
414        let h = m.render_head();
415        assert!(h.contains("<title>&lt;script&gt;</title>"));
416        assert!(h.contains("content=\"a &quot;quote&quot;\""));
417        assert!(h.contains("<link rel=\"canonical\" href=\"#\">"));
418        assert!(h.contains("<meta property=\"og:title\" content=\"&lt;script&gt;\">"));
419        assert!(h.contains("og:image:width"));
420        assert!(h.contains("as=\"font\" type=\"font/woff2\" crossorigin"));
421    }
422}