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