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 pub html_attributes: Vec<(String, String)>,
42 pub theme_colors: Vec<(String, String)>,
44}
45
46#[derive(Debug, Clone, Default, PartialEq, Eq)]
48pub struct LinkTag {
49 pub rel: String,
50 pub href: String,
51 pub mime: Option<String>,
52 pub title: Option<String>,
53}
54
55#[derive(Debug, Clone, Default, PartialEq, Eq)]
56pub struct Icon {
57 pub rel: String,
58 pub href: String,
59 pub sizes: Option<String>,
60 pub mime: Option<String>,
61}
62
63#[derive(Debug, Clone, Default, PartialEq, Eq)]
64pub struct OpenGraph {
65 pub title: Option<String>,
66 pub description: Option<String>,
67 pub url: Option<String>,
68 pub site_name: Option<String>,
69 pub kind: Option<String>,
70 pub locale: Option<String>,
71 pub images: Vec<OgImage>,
72}
73
74#[derive(Debug, Clone, Default, PartialEq, Eq)]
75pub struct OgImage {
76 pub url: String,
77 pub width: Option<u32>,
78 pub height: Option<u32>,
79 pub alt: Option<String>,
80}
81
82#[derive(Debug, Clone, Default, PartialEq, Eq)]
83pub struct Twitter {
84 pub card: Option<String>,
85 pub site: Option<String>,
86 pub creator: Option<String>,
87 pub title: Option<String>,
88 pub description: Option<String>,
89 pub images: Vec<String>,
90}
91
92#[derive(Debug, Clone, Default, PartialEq, Eq)]
93pub struct Preload {
94 pub href: String,
95 pub as_: String,
97 pub mime: Option<String>,
98 pub crossorigin: bool,
99}
100
101macro_rules! setters {
102 ($($name:ident),*) => {$(
103 pub fn $name(mut self, v: impl Into<String>) -> Self {
104 self.$name = Some(v.into());
105 self
106 }
107 )*};
108}
109
110impl Metadata {
111 pub fn new() -> Self {
112 Self::default()
113 }
114
115 setters!(title, title_template, description, canonical, robots, viewport, theme_color, color_scheme, manifest);
116
117 pub fn absolute_title(mut self, v: impl Into<String>) -> Self {
119 self.title = Some(v.into());
120 self.title_absolute = true;
121 self
122 }
123
124 pub fn keywords<I, S>(mut self, v: I) -> Self
125 where
126 I: IntoIterator<Item = S>,
127 S: Into<String>,
128 {
129 self.keywords = Some(v.into_iter().map(Into::into).collect());
130 self
131 }
132
133 pub fn authors<I, S>(mut self, v: I) -> Self
134 where
135 I: IntoIterator<Item = S>,
136 S: Into<String>,
137 {
138 self.authors = Some(v.into_iter().map(Into::into).collect());
139 self
140 }
141
142 pub fn icon(mut self, href: impl Into<String>) -> Self {
143 self.icons.get_or_insert_with(Vec::new).push(Icon {
144 rel: "icon".into(),
145 href: href.into(),
146 sizes: None,
147 mime: None,
148 });
149 self
150 }
151
152 pub fn icon_sized(mut self, href: impl Into<String>, sizes: impl Into<String>, mime: impl Into<String>) -> Self {
155 self.icons.get_or_insert_with(Vec::new).push(Icon {
156 rel: "icon".into(),
157 href: href.into(),
158 sizes: Some(sizes.into()),
159 mime: Some(mime.into()),
160 });
161 self
162 }
163
164 pub fn theme_color_for(mut self, media: impl Into<String>, color: impl Into<String>) -> Self {
170 self.theme_colors.push((media.into(), color.into()));
171 self
172 }
173
174 pub fn apple_touch_icon(mut self, href: impl Into<String>) -> Self {
175 self.icons.get_or_insert_with(Vec::new).push(Icon {
176 rel: "apple-touch-icon".into(),
177 href: href.into(),
178 sizes: None,
179 mime: None,
180 });
181 self
182 }
183
184 pub fn open_graph(mut self, og: OpenGraph) -> Self {
185 self.open_graph = Some(og);
186 self
187 }
188
189 pub fn twitter(mut self, tw: Twitter) -> Self {
190 self.twitter = Some(tw);
191 self
192 }
193
194 pub fn alternate(mut self, lang: impl Into<String>, href: impl Into<String>) -> Self {
195 self.alternates.get_or_insert_with(Vec::new).push((lang.into(), href.into()));
196 self
197 }
198
199 pub fn meta(mut self, name: impl Into<String>, content: impl Into<String>) -> Self {
200 self.other.push((name.into(), content.into()));
201 self
202 }
203
204 pub fn stylesheet(mut self, href: impl Into<String>) -> Self {
205 self.stylesheets.push(href.into());
206 self
207 }
208
209 pub fn preload_font(mut self, href: impl Into<String>) -> Self {
211 let href = href.into();
212 let mime = crate_mime(&href);
213 self.preloads.push(Preload { href, as_: "font".into(), mime, crossorigin: true });
214 self
215 }
216
217 pub fn preload_image(mut self, href: impl Into<String>) -> Self {
218 self.preloads.push(Preload { href: href.into(), as_: "image".into(), mime: None, crossorigin: false });
219 self
220 }
221
222 pub fn link(mut self, rel: impl Into<String>, href: impl Into<String>) -> Self {
224 self.links.push(LinkTag { rel: rel.into(), href: href.into(), ..Default::default() });
225 self
226 }
227
228 pub fn html_attribute(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
238 let name = name.into();
239 let value = value.into();
240 if let Some(slot) = self.html_attributes.iter_mut().find(|(n, _)| *n == name) {
241 slot.1 = value;
242 } else {
243 self.html_attributes.push((name, value));
244 }
245 self
246 }
247
248 pub fn feed(mut self, title: impl Into<String>, href: impl Into<String>, mime: impl Into<String>) -> Self {
252 self.links.push(LinkTag {
253 rel: "alternate".into(),
254 href: href.into(),
255 mime: Some(mime.into()),
256 title: Some(title.into()),
257 });
258 self
259 }
260
261 pub fn merge(mut self, child: Metadata) -> Metadata {
263 if let Some(t) = child.title {
264 self.title = Some(match (&self.title_template, child.title_absolute) {
265 (Some(tpl), false) => tpl.replace("%s", &t),
266 _ => t,
267 });
268 }
269 macro_rules! take {
270 ($($f:ident),*) => {$( if child.$f.is_some() { self.$f = child.$f; } )*};
271 }
272 take!(
273 title_template,
274 description,
275 keywords,
276 authors,
277 canonical,
278 robots,
279 viewport,
280 theme_color,
281 color_scheme,
282 manifest,
283 icons,
284 open_graph,
285 twitter,
286 alternates
287 );
288 for (k, v) in child.other {
289 if let Some(slot) = self.other.iter_mut().find(|(n, _)| *n == k) {
290 slot.1 = v;
291 } else {
292 self.other.push((k, v));
293 }
294 }
295 if !child.theme_colors.is_empty() {
296 self.theme_colors = child.theme_colors;
297 }
298 for (name, value) in child.html_attributes {
299 self = self.html_attribute(name, value);
300 }
301 for l in child.links {
302 if !self.links.contains(&l) {
303 self.links.push(l);
304 }
305 }
306 for s in child.stylesheets {
307 if !self.stylesheets.contains(&s) {
308 self.stylesheets.push(s);
309 }
310 }
311 for p in child.preloads {
312 if !self.preloads.contains(&p) {
313 self.preloads.push(p);
314 }
315 }
316 self
317 }
318
319 pub fn render_head(&self) -> String {
321 let mut h = String::with_capacity(512);
322 h.push_str("<meta charset=\"utf-8\">");
323 let viewport = self.viewport.as_deref().unwrap_or("width=device-width, initial-scale=1");
324 meta_name(&mut h, "viewport", viewport);
325 if let Some(t) = &self.title {
326 h.push_str("<title>");
327 h.push_str(&escape_text(t));
328 h.push_str("</title>");
329 }
330 if let Some(d) = &self.description {
331 meta_name(&mut h, "description", d);
332 }
333 if let Some(k) = &self.keywords {
334 meta_name(&mut h, "keywords", &k.join(", "));
335 }
336 if let Some(a) = &self.authors {
337 for author in a {
338 meta_name(&mut h, "author", author);
339 }
340 }
341 if let Some(r) = &self.robots {
342 meta_name(&mut h, "robots", r);
343 }
344 if let Some(c) = &self.theme_color {
345 meta_name(&mut h, "theme-color", c);
346 }
347 for (media, color) in &self.theme_colors {
348 h.push_str(&format!(
349 "<meta name=\"theme-color\" media=\"{}\" content=\"{}\">",
350 escape_attr(media),
351 escape_attr(color)
352 ));
353 }
354 if let Some(c) = &self.color_scheme {
355 meta_name(&mut h, "color-scheme", c);
356 }
357 if let Some(c) = &self.canonical {
358 link(&mut h, "canonical", c, &[]);
359 }
360 if let Some(alts) = &self.alternates {
361 for (lang, href) in alts {
362 link(&mut h, "alternate", href, &[("hreflang", lang)]);
363 }
364 }
365 if let Some(m) = &self.manifest {
366 link(&mut h, "manifest", m, &[]);
367 }
368 for l in &self.links {
369 let mut extra: Vec<(&str, &str)> = Vec::new();
370 if let Some(t) = &l.mime {
371 extra.push(("type", t));
372 }
373 if let Some(t) = &l.title {
374 extra.push(("title", t));
375 }
376 link(&mut h, &l.rel, &l.href, &extra);
377 }
378 if let Some(icons) = &self.icons {
379 for i in icons {
380 let mut extra = Vec::new();
381 if let Some(s) = &i.sizes {
382 extra.push(("sizes", s.as_str()));
383 }
384 if let Some(t) = &i.mime {
385 extra.push(("type", t.as_str()));
386 }
387 link(&mut h, &i.rel, &i.href, &extra);
388 }
389 }
390 if let Some(og) = &self.open_graph {
391 let title = og.title.as_ref().or(self.title.as_ref());
392 let desc = og.description.as_ref().or(self.description.as_ref());
393 for (p, v) in [
394 ("og:title", title),
395 ("og:description", desc),
396 ("og:url", og.url.as_ref()),
397 ("og:site_name", og.site_name.as_ref()),
398 ("og:type", og.kind.as_ref()),
399 ("og:locale", og.locale.as_ref()),
400 ] {
401 if let Some(v) = v {
402 meta_property(&mut h, p, v);
403 }
404 }
405 for img in &og.images {
406 meta_property(&mut h, "og:image", &img.url);
407 if let Some(w) = img.width {
408 meta_property(&mut h, "og:image:width", &w.to_string());
409 }
410 if let Some(hh) = img.height {
411 meta_property(&mut h, "og:image:height", &hh.to_string());
412 }
413 if let Some(a) = &img.alt {
414 meta_property(&mut h, "og:image:alt", a);
415 }
416 }
417 }
418 if let Some(tw) = &self.twitter {
419 for (n, v) in [
420 ("twitter:card", tw.card.as_ref()),
421 ("twitter:site", tw.site.as_ref()),
422 ("twitter:creator", tw.creator.as_ref()),
423 ("twitter:title", tw.title.as_ref().or(self.title.as_ref())),
424 ("twitter:description", tw.description.as_ref().or(self.description.as_ref())),
425 ] {
426 if let Some(v) = v {
427 meta_name(&mut h, n, v);
428 }
429 }
430 for img in &tw.images {
431 meta_name(&mut h, "twitter:image", img);
432 }
433 }
434 for (n, v) in &self.other {
435 meta_name(&mut h, n, v);
436 }
437 for p in &self.preloads {
438 h.push_str(&format!(
439 "<link rel=\"preload\" href=\"{}\" as=\"{}\"",
440 escape_attr(&p.href),
441 escape_attr(&p.as_)
442 ));
443 if let Some(m) = &p.mime {
444 h.push_str(&format!(" type=\"{}\"", escape_attr(m)));
445 }
446 if p.crossorigin {
447 h.push_str(" crossorigin");
448 }
449 h.push('>');
450 }
451 for s in &self.stylesheets {
452 link(&mut h, "stylesheet", s, &[]);
453 }
454 h
455 }
456}
457
458fn crate_mime(href: &str) -> Option<String> {
459 let ext = href.rsplit('.').next()?.to_ascii_lowercase();
460 Some(
461 match ext.as_str() {
462 "woff2" => "font/woff2",
463 "woff" => "font/woff",
464 "ttf" => "font/ttf",
465 "otf" => "font/otf",
466 _ => return None,
467 }
468 .into(),
469 )
470}
471
472fn meta_name(h: &mut String, name: &str, content: &str) {
473 h.push_str(&format!("<meta name=\"{}\" content=\"{}\">", escape_attr(name), escape_attr(content)));
474}
475
476fn meta_property(h: &mut String, prop: &str, content: &str) {
477 h.push_str(&format!("<meta property=\"{}\" content=\"{}\">", escape_attr(prop), escape_attr(content)));
478}
479
480fn link(h: &mut String, rel: &str, href: &str, extra: &[(&str, &str)]) {
481 let href = if crate::escape::is_safe_url(href) { href } else { "#" };
482 h.push_str(&format!("<link rel=\"{}\" href=\"{}\"", escape_attr(rel), escape_attr(href)));
483 for (k, v) in extra {
484 h.push_str(&format!(" {k}=\"{}\"", escape_attr(v)));
485 }
486 h.push('>');
487}
488
489#[cfg(test)]
490mod tests {
491 use super::*;
492
493 #[test]
494 fn merges_with_templates() {
495 let root = Metadata::new().title("Acme").title_template("%s | Acme").description("root");
496 let blog = Metadata::new().title("Blog").title_template("%s – Blog | Acme");
497 let post = Metadata::new().title("Hello").keywords(["rust"]);
498 let merged = Metadata::default().merge(root.clone()).merge(blog).merge(post);
499 assert_eq!(merged.title.as_deref(), Some("Hello – Blog | Acme"));
500 assert_eq!(merged.description.as_deref(), Some("root"));
501 let merged = Metadata::default().merge(root.clone());
502 assert_eq!(merged.title.as_deref(), Some("Acme"), "template does not apply to the same segment");
503 let merged = Metadata::default().merge(root).merge(Metadata::new().absolute_title("Standalone"));
504 assert_eq!(merged.title.as_deref(), Some("Standalone"));
505 }
506
507 #[test]
508 fn sized_icons_and_theme_colors_per_scheme() {
509 let root = Metadata::new()
510 .theme_color("#0d1b2a")
511 .theme_color_for("(prefers-color-scheme: light)", "#fafaf7")
512 .theme_color_for("(prefers-color-scheme: dark)", "#0d1b2a")
513 .icon_sized("/favicon-32x32.png", "32x32", "image/png");
514 let h = Metadata::default().merge(root.clone()).render_head();
515 assert!(h.contains(r##"<meta name="theme-color" content="#0d1b2a">"##), "{h}");
516 assert!(h.contains(r##"<meta name="theme-color" media="(prefers-color-scheme: light)" content="#fafaf7">"##));
517 assert!(h.contains(r#"<link rel="icon" href="/favicon-32x32.png" sizes="32x32" type="image/png">"#));
518 let page = Metadata::new().theme_color_for("all", "\"x");
520 let merged = Metadata::default().merge(root).merge(page);
521 assert_eq!(merged.theme_colors, [("all".to_owned(), "\"x".to_owned())]);
522 assert!(merged.render_head().contains(r#"media="all" content=""x""#));
523 }
524
525 #[test]
526 fn html_attributes_merge_child_wins() {
527 let root = Metadata::new().html_attribute("data-theme", "pass-point").html_attribute("class", "dark");
528 let page = Metadata::new().html_attribute("class", "light").html_attribute("lang", "de");
529 let merged = Metadata::default().merge(root).merge(page);
530 assert_eq!(
531 merged.html_attributes,
532 [
533 ("data-theme".into(), "pass-point".into()),
534 ("class".into(), "light".into()),
535 ("lang".into(), "de".into())
536 ]
537 );
538 let m = Metadata::new().html_attribute("dir", "ltr").html_attribute("dir", "rtl");
540 assert_eq!(m.html_attributes, [("dir".into(), "rtl".into())]);
541 }
542
543 #[test]
544 fn renders_escaped_head() {
545 let m = Metadata::new()
546 .title("<script>")
547 .description("a \"quote\"")
548 .canonical("javascript:alert(1)")
549 .open_graph(OpenGraph {
550 images: vec![OgImage { url: "/og.png".into(), width: Some(1200), ..Default::default() }],
551 ..Default::default()
552 })
553 .preload_font("/fonts/inter.woff2");
554 let h = m.render_head();
555 assert!(h.contains("<title><script></title>"));
556 assert!(h.contains("content=\"a "quote"\""));
557 assert!(h.contains("<link rel=\"canonical\" href=\"#\">"));
558 assert!(h.contains("<meta property=\"og:title\" content=\"<script>\">"));
559 assert!(h.contains("og:image:width"));
560 assert!(h.contains("as=\"font\" type=\"font/woff2\" crossorigin"));
561 }
562}