next-rust-view 0.1.2

The Next Rust view layer: an escaping-by-default HTML DSL, components, metadata and a streaming renderer.
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
//! Document metadata (`<head>` contents).
//!
//! Layouts and pages each return a [`Metadata`]; the framework merges them
//! from the root layout down to the page with [`Metadata::merge`]: every
//! field set by a child overrides the parent's value, and a parent's
//! `title_template` (e.g. `"%s | Acme"`) is applied to titles defined *below*
//! it.

use crate::escape::{escape_attr, escape_text};

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Metadata {
    pub title: Option<String>,
    /// Applied to descendant titles; `%s` is replaced by the child title.
    pub title_template: Option<String>,
    /// When true, this title ignores ancestor templates.
    pub title_absolute: bool,
    pub description: Option<String>,
    pub keywords: Option<Vec<String>>,
    pub authors: Option<Vec<String>>,
    pub canonical: Option<String>,
    pub robots: Option<String>,
    pub viewport: Option<String>,
    pub theme_color: Option<String>,
    pub color_scheme: Option<String>,
    pub manifest: Option<String>,
    pub icons: Option<Vec<Icon>>,
    pub open_graph: Option<OpenGraph>,
    pub twitter: Option<Twitter>,
    /// `hreflang` alternates: (language, url).
    pub alternates: Option<Vec<(String, String)>>,
    /// Extra `<meta name=.. content=..>` entries.
    pub other: Vec<(String, String)>,
    /// External stylesheets (`<link rel="stylesheet">`).
    pub stylesheets: Vec<String>,
    /// Preloaded resources (fonts, images).
    pub preloads: Vec<Preload>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Icon {
    pub rel: String,
    pub href: String,
    pub sizes: Option<String>,
    pub mime: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct OpenGraph {
    pub title: Option<String>,
    pub description: Option<String>,
    pub url: Option<String>,
    pub site_name: Option<String>,
    pub kind: Option<String>,
    pub locale: Option<String>,
    pub images: Vec<OgImage>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct OgImage {
    pub url: String,
    pub width: Option<u32>,
    pub height: Option<u32>,
    pub alt: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Twitter {
    pub card: Option<String>,
    pub site: Option<String>,
    pub creator: Option<String>,
    pub title: Option<String>,
    pub description: Option<String>,
    pub images: Vec<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Preload {
    pub href: String,
    /// `font`, `image`, `style`, `script`, `fetch`.
    pub as_: String,
    pub mime: Option<String>,
    pub crossorigin: bool,
}

macro_rules! setters {
    ($($name:ident),*) => {$(
        pub fn $name(mut self, v: impl Into<String>) -> Self {
            self.$name = Some(v.into());
            self
        }
    )*};
}

impl Metadata {
    pub fn new() -> Self {
        Self::default()
    }

    setters!(title, title_template, description, canonical, robots, viewport, theme_color, color_scheme, manifest);

    /// A title that ignores ancestor templates.
    pub fn absolute_title(mut self, v: impl Into<String>) -> Self {
        self.title = Some(v.into());
        self.title_absolute = true;
        self
    }

    pub fn keywords<I, S>(mut self, v: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.keywords = Some(v.into_iter().map(Into::into).collect());
        self
    }

    pub fn authors<I, S>(mut self, v: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.authors = Some(v.into_iter().map(Into::into).collect());
        self
    }

    pub fn icon(mut self, href: impl Into<String>) -> Self {
        self.icons.get_or_insert_with(Vec::new).push(Icon {
            rel: "icon".into(),
            href: href.into(),
            sizes: None,
            mime: None,
        });
        self
    }

    pub fn apple_touch_icon(mut self, href: impl Into<String>) -> Self {
        self.icons.get_or_insert_with(Vec::new).push(Icon {
            rel: "apple-touch-icon".into(),
            href: href.into(),
            sizes: None,
            mime: None,
        });
        self
    }

    pub fn open_graph(mut self, og: OpenGraph) -> Self {
        self.open_graph = Some(og);
        self
    }

    pub fn twitter(mut self, tw: Twitter) -> Self {
        self.twitter = Some(tw);
        self
    }

    pub fn alternate(mut self, lang: impl Into<String>, href: impl Into<String>) -> Self {
        self.alternates.get_or_insert_with(Vec::new).push((lang.into(), href.into()));
        self
    }

    pub fn meta(mut self, name: impl Into<String>, content: impl Into<String>) -> Self {
        self.other.push((name.into(), content.into()));
        self
    }

    pub fn stylesheet(mut self, href: impl Into<String>) -> Self {
        self.stylesheets.push(href.into());
        self
    }

    /// Preload a font file (adds `crossorigin`, required for fonts).
    pub fn preload_font(mut self, href: impl Into<String>) -> Self {
        let href = href.into();
        let mime = crate_mime(&href);
        self.preloads.push(Preload { href, as_: "font".into(), mime, crossorigin: true });
        self
    }

    pub fn preload_image(mut self, href: impl Into<String>) -> Self {
        self.preloads.push(Preload { href: href.into(), as_: "image".into(), mime: None, crossorigin: false });
        self
    }

    /// Merge `child` into `self` (child wins).
    pub fn merge(mut self, child: Metadata) -> Metadata {
        if let Some(t) = child.title {
            self.title = Some(match (&self.title_template, child.title_absolute) {
                (Some(tpl), false) => tpl.replace("%s", &t),
                _ => t,
            });
        }
        macro_rules! take {
            ($($f:ident),*) => {$( if child.$f.is_some() { self.$f = child.$f; } )*};
        }
        take!(
            title_template,
            description,
            keywords,
            authors,
            canonical,
            robots,
            viewport,
            theme_color,
            color_scheme,
            manifest,
            icons,
            open_graph,
            twitter,
            alternates
        );
        for (k, v) in child.other {
            if let Some(slot) = self.other.iter_mut().find(|(n, _)| *n == k) {
                slot.1 = v;
            } else {
                self.other.push((k, v));
            }
        }
        for s in child.stylesheets {
            if !self.stylesheets.contains(&s) {
                self.stylesheets.push(s);
            }
        }
        for p in child.preloads {
            if !self.preloads.contains(&p) {
                self.preloads.push(p);
            }
        }
        self
    }

    /// Render `<head>` contents.
    pub fn render_head(&self) -> String {
        let mut h = String::with_capacity(512);
        h.push_str("<meta charset=\"utf-8\">");
        let viewport = self.viewport.as_deref().unwrap_or("width=device-width, initial-scale=1");
        meta_name(&mut h, "viewport", viewport);
        if let Some(t) = &self.title {
            h.push_str("<title>");
            h.push_str(&escape_text(t));
            h.push_str("</title>");
        }
        if let Some(d) = &self.description {
            meta_name(&mut h, "description", d);
        }
        if let Some(k) = &self.keywords {
            meta_name(&mut h, "keywords", &k.join(", "));
        }
        if let Some(a) = &self.authors {
            for author in a {
                meta_name(&mut h, "author", author);
            }
        }
        if let Some(r) = &self.robots {
            meta_name(&mut h, "robots", r);
        }
        if let Some(c) = &self.theme_color {
            meta_name(&mut h, "theme-color", c);
        }
        if let Some(c) = &self.color_scheme {
            meta_name(&mut h, "color-scheme", c);
        }
        if let Some(c) = &self.canonical {
            link(&mut h, "canonical", c, &[]);
        }
        if let Some(alts) = &self.alternates {
            for (lang, href) in alts {
                link(&mut h, "alternate", href, &[("hreflang", lang)]);
            }
        }
        if let Some(m) = &self.manifest {
            link(&mut h, "manifest", m, &[]);
        }
        if let Some(icons) = &self.icons {
            for i in icons {
                let mut extra = Vec::new();
                if let Some(s) = &i.sizes {
                    extra.push(("sizes", s.as_str()));
                }
                if let Some(t) = &i.mime {
                    extra.push(("type", t.as_str()));
                }
                link(&mut h, &i.rel, &i.href, &extra);
            }
        }
        if let Some(og) = &self.open_graph {
            let title = og.title.as_ref().or(self.title.as_ref());
            let desc = og.description.as_ref().or(self.description.as_ref());
            for (p, v) in [
                ("og:title", title),
                ("og:description", desc),
                ("og:url", og.url.as_ref()),
                ("og:site_name", og.site_name.as_ref()),
                ("og:type", og.kind.as_ref()),
                ("og:locale", og.locale.as_ref()),
            ] {
                if let Some(v) = v {
                    meta_property(&mut h, p, v);
                }
            }
            for img in &og.images {
                meta_property(&mut h, "og:image", &img.url);
                if let Some(w) = img.width {
                    meta_property(&mut h, "og:image:width", &w.to_string());
                }
                if let Some(hh) = img.height {
                    meta_property(&mut h, "og:image:height", &hh.to_string());
                }
                if let Some(a) = &img.alt {
                    meta_property(&mut h, "og:image:alt", a);
                }
            }
        }
        if let Some(tw) = &self.twitter {
            for (n, v) in [
                ("twitter:card", tw.card.as_ref()),
                ("twitter:site", tw.site.as_ref()),
                ("twitter:creator", tw.creator.as_ref()),
                ("twitter:title", tw.title.as_ref().or(self.title.as_ref())),
                ("twitter:description", tw.description.as_ref().or(self.description.as_ref())),
            ] {
                if let Some(v) = v {
                    meta_name(&mut h, n, v);
                }
            }
            for img in &tw.images {
                meta_name(&mut h, "twitter:image", img);
            }
        }
        for (n, v) in &self.other {
            meta_name(&mut h, n, v);
        }
        for p in &self.preloads {
            h.push_str(&format!(
                "<link rel=\"preload\" href=\"{}\" as=\"{}\"",
                escape_attr(&p.href),
                escape_attr(&p.as_)
            ));
            if let Some(m) = &p.mime {
                h.push_str(&format!(" type=\"{}\"", escape_attr(m)));
            }
            if p.crossorigin {
                h.push_str(" crossorigin");
            }
            h.push('>');
        }
        for s in &self.stylesheets {
            link(&mut h, "stylesheet", s, &[]);
        }
        h
    }
}

fn crate_mime(href: &str) -> Option<String> {
    let ext = href.rsplit('.').next()?.to_ascii_lowercase();
    Some(
        match ext.as_str() {
            "woff2" => "font/woff2",
            "woff" => "font/woff",
            "ttf" => "font/ttf",
            "otf" => "font/otf",
            _ => return None,
        }
        .into(),
    )
}

fn meta_name(h: &mut String, name: &str, content: &str) {
    h.push_str(&format!("<meta name=\"{}\" content=\"{}\">", escape_attr(name), escape_attr(content)));
}

fn meta_property(h: &mut String, prop: &str, content: &str) {
    h.push_str(&format!("<meta property=\"{}\" content=\"{}\">", escape_attr(prop), escape_attr(content)));
}

fn link(h: &mut String, rel: &str, href: &str, extra: &[(&str, &str)]) {
    let href = if crate::escape::is_safe_url(href) { href } else { "#" };
    h.push_str(&format!("<link rel=\"{}\" href=\"{}\"", escape_attr(rel), escape_attr(href)));
    for (k, v) in extra {
        h.push_str(&format!(" {k}=\"{}\"", escape_attr(v)));
    }
    h.push('>');
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn merges_with_templates() {
        let root = Metadata::new().title("Acme").title_template("%s | Acme").description("root");
        let blog = Metadata::new().title("Blog").title_template("%s – Blog | Acme");
        let post = Metadata::new().title("Hello").keywords(["rust"]);
        let merged = Metadata::default().merge(root.clone()).merge(blog).merge(post);
        assert_eq!(merged.title.as_deref(), Some("Hello – Blog | Acme"));
        assert_eq!(merged.description.as_deref(), Some("root"));
        let merged = Metadata::default().merge(root.clone());
        assert_eq!(merged.title.as_deref(), Some("Acme"), "template does not apply to the same segment");
        let merged = Metadata::default().merge(root).merge(Metadata::new().absolute_title("Standalone"));
        assert_eq!(merged.title.as_deref(), Some("Standalone"));
    }

    #[test]
    fn renders_escaped_head() {
        let m = Metadata::new()
            .title("<script>")
            .description("a \"quote\"")
            .canonical("javascript:alert(1)")
            .open_graph(OpenGraph {
                images: vec![OgImage { url: "/og.png".into(), width: Some(1200), ..Default::default() }],
                ..Default::default()
            })
            .preload_font("/fonts/inter.woff2");
        let h = m.render_head();
        assert!(h.contains("<title>&lt;script&gt;</title>"));
        assert!(h.contains("content=\"a &quot;quote&quot;\""));
        assert!(h.contains("<link rel=\"canonical\" href=\"#\">"));
        assert!(h.contains("<meta property=\"og:title\" content=\"&lt;script&gt;\">"));
        assert!(h.contains("og:image:width"));
        assert!(h.contains("as=\"font\" type=\"font/woff2\" crossorigin"));
    }
}