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
#![cfg_attr(feature = "nightly", deny(missing_docs))]
#![cfg_attr(feature = "nightly", feature(external_doc))]
#![cfg_attr(feature = "nightly", doc(include = "../README.md"))]
#![cfg_attr(test, deny(warnings))]
#![forbid(unsafe_code, missing_debug_implementations)]

extern crate css_rel_preload;

const DOCTYPE: &str = "<!DOCTYPE html>";
const CHARSET: &str = r#"<meta charset="utf-8">"#;
const VIEWPORT: &str =
  r#"<meta name="viewport" content="width=device-width, initial-scale=1.0">"#;
const HTML_CLOSE: &str = "</html>";
const HEAD_OPEN: &str = "<head>";
const HEAD_CLOSE: &str = "</head>";

use std::default::Default;

/// Create a new HTML builder.
#[derive(Debug, Clone, Default)]
pub struct Builder<'b> {
  color: Option<String>,
  desc: Option<String>,
  lang: &'b str,
  favicon: Option<String>,
  fonts: Vec<String>,
  manifest: Option<String>,
  scripts: Vec<String>,
  styles: Vec<String>,
  title: Option<String>,
  body: Option<&'b str>,
  has_async_style: bool,
}

impl<'b> Builder<'b> {
  /// Create a new instance from an HTML body, including `<body></body>` tags.
  pub fn new() -> Self {
    Self {
      lang: "en-US",
      ..Default::default()
    }
  }

  /// Add a body to the document. The body must include `<body></body>` tags.
  pub fn raw_body(mut self, body: &'b str) -> Self {
    self.body = Some(body);
    self
  }

  /// Set the document language.
  pub fn lang(mut self, lang: &'b str) -> Self {
    self.lang = lang;
    self
  }

  /// Add a `<meta name="description">` tag.
  pub fn description(mut self, desc: &str) -> Self {
    let val = format!(r#"<meta name="description" content="{}">"#, desc);
    self.desc = Some(val);
    self
  }

  /// Add a `<meta name="theme-color">` tag.
  pub fn theme_color(mut self, color: &str) -> Self {
    let val = format!(r#"<meta name="theme-color" content="{}">"#, color);
    self.color = Some(val);
    self
  }

  /// Add a `<title>` tag.
  pub fn title(mut self, title: &str) -> Self {
    let val = format!(r#"<title>{}</title>"#, title);
    self.title = Some(val);
    self
  }

  /// Add a `<script defer>` tag. This is ideal for loading scripts that are
  /// important for the main application, but shouldn't interfere with the
  /// initial rendering.
  // TODO: also allow passing a sha512
  pub fn script(mut self, src: &str) -> Self {
    let val = format!(r#"<script src="{}" defer></script>"#, src);
    self.scripts.push(val);
    self
  }

  /// Add a `<link rel="prefetch">` tag. This is ideal for loading scripts in
  /// the background after the main application has loaded.
  // TODO: also allow passing a sha512
  pub fn lazy_script(mut self, src: &str) -> Self {
    let val = format!(r#"<link rel="prefetch" href="{}">"#, src);
    self.scripts.push(val);
    self
  }

  /// Add a `<script>` tag. This is ideal for loading scripts that should be
  /// loaded before any rendering can start.
  // TODO: also allow passing a sha512
  pub fn blocking_script(mut self, src: &str) -> Self {
    let val = format!(r#"<script src="{}"></script>"#, src);
    self.scripts.push(val);
    self
  }

  /// Add a `<script></script>` tag. This is ideal for loading custom scripts
  /// that are essential for loading.
  // TODO: also allow passing a sha512
  pub fn inline_script(mut self, src: &str) -> Self {
    let val = format!(r#"<script>{}</script>"#, src);
    self.scripts.push(val);
    self
  }

  /// Add a non-blocking `<link as="style">` tag. This is ideal for including
  /// styles that aren't essential for an initial render pass.
  ///
  /// Generally this should be combined with `.inline_style()` to optimize a
  /// render pipeline.
  ///
  /// `onerror` exists because of a bug in firefox. See https://github.com/filamentgroup/loadCSS/issues/246 for more details
  // TODO: also allow passing a sha512
  pub fn style(mut self, src: &str) -> Self {
    let val = format!(r#"<link rel="preload" as="style" href="{}" onload="this.rel='stylesheet'" onerror="this.rel='stylesheet'">"#, src);
    self.styles.push(val);

    if !self.has_async_style {
      self = self.inline_script(css_rel_preload::CSS_REL_PRELOAD);
      self.has_async_style = true;
    }

    self
  }

  /// Add an inline `<style>` tag. This is ideal for including styles that
  /// should be available for an initial render pass.
  ///
  /// Generally this should be combined with `.style()` to optimize a render
  /// pipeline.
  // TODO: also allow passing a sha512
  pub fn inline_style(mut self, src: &str) -> Self {
    let val = format!(r#"<style>{}</style>"#, src);
    self.styles.push(val);
    self
  }

  /// Add a blocking `<link rel="stylesheet">` tag. This is ideal for externally
  /// loading scripts that should be loaded before any rendering can be
  /// initialized.
  // TODO: also allow passing a sha512
  pub fn blocking_style(mut self, src: &str) -> Self {
    let val = format!(r#"<link rel="stylesheet" href="{}">"#, src);
    self.styles.push(val);
    self
  }

  /// Add a favicon.
  pub fn favicon(mut self, src: &str) -> Self {
    let val =
      format!(r#"<link rel="icon" type="image/x-icon" href="{}">"#, src);
    self.favicon = Some(val);
    self
  }

  /// Add a `manifest.json` link.
  pub fn manifest(mut self, src: &str) -> Self {
    let val = format!(r#"<link rel="manifest" href="{}">"#, src);
    self.manifest = Some(val);
    self
  }

  /// Add a `<link as="font">` tag.
  pub fn font(mut self, src: &str) -> Self {
    let val = format!(
      r#"<link rel="preload" as="font" crossorigin href="{}">"#,
      src
    );
    self.fonts.push(val);
    self
  }

  /// Create an HTML document.
  pub fn build(self) -> String {
    let mut html: String = DOCTYPE.into();
    html.push_str(&format!(r#"<html lang="{}">"#, self.lang));
    html.push_str(HEAD_OPEN);
    html.push_str(CHARSET);
    html.push_str(VIEWPORT);
    if let Some(title) = self.title {
      html.push_str(&title);
    }
    if let Some(desc) = self.desc {
      html.push_str(&desc);
    }

    for script in self.scripts {
      html.push_str(&script);
    }
    for style in self.styles {
      html.push_str(&style);
    }
    for font in self.fonts {
      html.push_str(&font);
    }
    if let Some(manifest) = self.manifest {
      html.push_str(&manifest);
    }

    if let Some(color) = self.color {
      html.push_str(&color);
    }
    if let Some(favicon) = self.favicon {
      html.push_str(&favicon);
    }
    html.push_str(HEAD_CLOSE);
    if let Some(body) = self.body {
      html.push_str(&body);
    }
    html.push_str(HTML_CLOSE);
    html
  }
}