1use std::fs;
5use std::path::Path;
6use std::time::UNIX_EPOCH;
7const SIMPLE_CSS: &str = include_str!("../assets/simple.min.css");
8const APP_DISPLAY_NAME: &str = "mdo";
9const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
10
11const MDO_DEFAULT_TYPOGRAPHY_CSS: &str = include_str!("../assets/mdo-default-typography.css");
15
16const GFM_ALERTS_CSS: &str = r#"
25:root{--alert-note:#0969da;--alert-tip:#1a7f37;--alert-important:#8250df;--alert-warning:#9a6700;--alert-caution:#cf222e}
26@media (prefers-color-scheme: dark){:root{--alert-note:#58a6ff;--alert-tip:#3fb950;--alert-important:#a371f7;--alert-warning:#d29922;--alert-caution:#f85149}}
27:root[data-theme="light"]{--alert-note:#0969da;--alert-tip:#1a7f37;--alert-important:#8250df;--alert-warning:#9a6700;--alert-caution:#cf222e}
28:root[data-theme="dark"]{--alert-note:#58a6ff;--alert-tip:#3fb950;--alert-important:#a371f7;--alert-warning:#d29922;--alert-caution:#f85149}
29blockquote[class^="markdown-alert-"]{--alert-color:var(--accent);border-left:.3rem solid var(--alert-color);background:var(--accent-bg);padding:.75rem 1rem}
30blockquote.markdown-alert-note{--alert-color:var(--alert-note)}blockquote.markdown-alert-tip{--alert-color:var(--alert-tip)}blockquote.markdown-alert-important{--alert-color:var(--alert-important)}blockquote.markdown-alert-warning{--alert-color:var(--alert-warning)}blockquote.markdown-alert-caution{--alert-color:var(--alert-caution)}
31"#;
32
33const THEME_TOGGLE: &str = r#"<style id="mdo-theme-toggle">
58:root[data-theme="light"]{color-scheme:light;--bg:#fff;--accent-bg:#f5f7ff;--text:#212121;--text-light:#585858;--accent:#0d47a1;--accent-hover:#1266e2;--accent-text:var(--bg);--code:#d81b60;--preformatted:#444;--disabled:#efefef}
59:root[data-theme="dark"]{color-scheme:dark;--bg:#212121;--accent-bg:#2b2b2b;--text:#dcdcdc;--text-light:#ababab;--accent:#ffb300;--accent-hover:#ffe099;--accent-text:var(--bg);--code:#f06292;--preformatted:#ccc;--disabled:#111}
60:root[data-theme="dark"] img,:root[data-theme="dark"] video{opacity:.8}
61#theme-toggle{position:fixed;top:.75rem;right:.75rem;z-index:1000;padding:.25rem .6rem;font-size:1rem;line-height:1;cursor:pointer;border-radius:var(--standard-border-radius);border:var(--border-width) solid var(--border);background:var(--accent-bg);color:var(--text)}
62@media (max-width:55rem){body{padding-top:2.75rem}}
63@media print{#theme-toggle{display:none}}
64</style>
65<script>
66(function(){
67 var read=function(){try{return localStorage.getItem('theme')}catch(e){return null}};
68 var apply=function(t){document.documentElement.dataset.theme=t;};
69 var mq=matchMedia('(prefers-color-scheme: dark)');
70 var saved=read();
71 var manual=saved!==null;
72 apply(saved||(mq.matches?'dark':'light'));
73 document.addEventListener('DOMContentLoaded',function(){
74 var b=document.createElement('button');
75 b.id='theme-toggle';b.type='button';
76 var sync=function(){
77 var dark=document.documentElement.dataset.theme==='dark';
78 b.textContent=dark?'\u2600':'\u263E';
79 var label=dark?'Switch to light theme':'Switch to dark theme';
80 b.title=label;
81 b.setAttribute('aria-label',label);
82 };
83 b.onclick=function(){
84 var next=document.documentElement.dataset.theme==='dark'?'light':'dark';
85 apply(next);
86 manual=true;
87 try{localStorage.setItem('theme',next)}catch(e){}
88 sync();
89 };
90 if(mq.addEventListener){
91 mq.addEventListener('change',function(e){
92 if(!manual){apply(e.matches?'dark':'light');sync();}
93 });
94 }
95 document.body.appendChild(b);
96 sync();
97 });
98})();
99</script>
100"#;
101pub(crate) fn wrap_html5(
104 body: &str,
105 title: &str,
106 base_href: Option<&str>,
107 css_override: Option<&str>,
108 highlight_css: Option<&str>,
109 source_modified_unix_secs: Option<u64>,
110) -> String {
111 let base_tag = match base_href {
116 Some(href) => format!("<base href=\"{}\">\n", html_escape(href)),
117 None => String::new(),
118 };
119 let css_override_block = css_override
120 .filter(|css| !css.trim().is_empty())
121 .map(|css| {
122 format!(
123 "<style id=\"mdo-css-override\">\n/* Custom CSS from --css */\n{}\n</style>\n",
124 escape_style_end_tags(css)
125 )
126 })
127 .unwrap_or_default();
128 let mdo_default_typography = format!(
129 "<style id=\"mdo-default-typography\">\n{}\n</style>\n",
130 escape_style_end_tags(MDO_DEFAULT_TYPOGRAPHY_CSS)
131 );
132 let highlight_css = highlight_css.unwrap_or_default();
133 let generator = format!("{APP_DISPLAY_NAME} {APP_VERSION}");
136 let source_meta = source_modified_unix_secs
142 .map(|secs| {
143 let machine = utc_datetime_from_unix_secs(secs);
144 let human = human_utc_datetime_from_unix_secs(secs);
145 format!(
146 "<footer class=\"mdo-source-meta\">Source modified: <time datetime=\"{machine}\">{human}</time></footer>\n\
147 <script>\n\
148 (function(){{var t=document.querySelector('.mdo-source-meta time');if(!t)return;var d=new Date(t.getAttribute('datetime'));if(isNaN(d))return;try{{t.textContent=d.toLocaleString(undefined,{{year:'numeric',month:'long',day:'numeric',hour:'numeric',minute:'2-digit'}});}}catch(e){{}}}})();\n\
149 </script>\n",
150 machine = html_escape(&machine),
151 human = html_escape(&human),
152 )
153 })
154 .unwrap_or_default();
155 format!(
156 "<!DOCTYPE html>\n\
157 <html lang=\"en\">\n\
158 <head>\n\
159 <meta charset=\"utf-8\">\n\
160 <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
161 <meta name=\"generator\" content=\"{generator}\">\n\
162 {base_tag}\
163 <title>{title}</title>\n\
164 <style>\n{css}\n{gfm_alerts_css}\n{highlight_css}\n.mdo-source-meta{{margin-top:3rem;border:0;padding:1rem 0 1.5rem;font-size:.8rem;line-height:1.4;color:var(--text-light);text-align:center}}\n</style>\n\
165 {theme_toggle}\
166 {mdo_default_typography}\
167 {css_override_block}\
168 </head>\n\
169 <body>\n\
170 <main>\n{body}\n</main>\n\
171 {source_meta}\
172 </body>\n\
173 </html>\n",
174 generator = html_escape(&generator),
175 base_tag = base_tag,
176 title = html_escape(title),
177 css = SIMPLE_CSS,
178 gfm_alerts_css = GFM_ALERTS_CSS,
179 highlight_css = highlight_css,
180 theme_toggle = THEME_TOGGLE, mdo_default_typography = mdo_default_typography,
182 css_override_block = css_override_block,
183 body = body,
184 source_meta = source_meta,
185 )
186}
187
188fn escape_style_end_tags(css: &str) -> String {
189 const STYLE_END_PREFIX: &[u8] = b"</style";
190
191 let mut escaped = String::with_capacity(css.len());
192 let bytes = css.as_bytes();
193 let mut i = 0;
194
195 while i < css.len() {
196 if i + STYLE_END_PREFIX.len() <= css.len()
197 && bytes[i..i + STYLE_END_PREFIX.len()].eq_ignore_ascii_case(STYLE_END_PREFIX)
198 {
199 escaped.push_str("<\\/style");
200 i += STYLE_END_PREFIX.len();
201 } else {
202 let ch = css[i..]
203 .chars()
204 .next()
205 .expect("index should always point at a char boundary");
206 escaped.push(ch);
207 i += ch.len_utf8();
208 }
209 }
210
211 escaped
212}
213
214const MONTH_NAMES: [&str; 12] = [
215 "January",
216 "February",
217 "March",
218 "April",
219 "May",
220 "June",
221 "July",
222 "August",
223 "September",
224 "October",
225 "November",
226 "December",
227];
228
229pub(crate) fn source_modified_unix_secs(input: &Path) -> Option<u64> {
232 fs::metadata(input)
233 .and_then(|metadata| metadata.modified())
234 .ok()
235 .and_then(|mtime| mtime.duration_since(UNIX_EPOCH).ok())
236 .map(|elapsed| elapsed.as_secs())
237}
238
239fn utc_datetime_from_unix_secs(secs: u64) -> String {
241 let days = (secs / 86_400) as i64;
242 let (year, month, day) = civil_from_days(days);
243 let seconds_of_day = secs % 86_400;
244 let hour = seconds_of_day / 3_600;
245 let minute = (seconds_of_day % 3_600) / 60;
246 let second = seconds_of_day % 60;
247
248 format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
249}
250
251fn human_utc_datetime_from_unix_secs(secs: u64) -> String {
254 let days = (secs / 86_400) as i64;
255 let (year, month, day) = civil_from_days(days);
256 let seconds_of_day = secs % 86_400;
257 let hour24 = seconds_of_day / 3_600;
258 let minute = (seconds_of_day % 3_600) / 60;
259 let (hour12, meridiem) = match hour24 {
260 0 => (12, "AM"),
261 1..=11 => (hour24, "AM"),
262 12 => (12, "PM"),
263 _ => (hour24 - 12, "PM"),
264 };
265 let month_name = MONTH_NAMES[(month - 1) as usize];
266
267 format!("{month_name} {day}, {year}, {hour12}:{minute:02} {meridiem} UTC")
268}
269
270fn civil_from_days(days_since_unix_epoch: i64) -> (i64, i64, i64) {
271 let z = days_since_unix_epoch + 719_468;
273 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
274 let doe = z - era * 146_097;
275 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
276 let y = yoe + era * 400;
277 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
278 let mp = (5 * doy + 2) / 153;
279 let day = doy - (153 * mp + 2) / 5 + 1;
280 let month = mp + if mp < 10 { 3 } else { -9 };
281 let year = y + if month <= 2 { 1 } else { 0 };
282
283 (year, month, day)
284}
285
286fn html_escape(s: &str) -> String {
287 s.replace('&', "&")
288 .replace('<', "<")
289 .replace('>', ">")
290 .replace('"', """)
291}
292#[cfg(test)]
293mod tests {
294 use super::*;
295 #[test]
296 fn formats_unix_timestamps_as_machine_utc_datetimes() {
297 assert_eq!(utc_datetime_from_unix_secs(0), "1970-01-01T00:00:00Z");
298 assert_eq!(
299 utc_datetime_from_unix_secs(951_827_696),
300 "2000-02-29T12:34:56Z"
301 );
302 }
303
304 #[test]
305 fn formats_unix_timestamps_as_readable_utc_datetimes() {
306 assert_eq!(
308 human_utc_datetime_from_unix_secs(0),
309 "January 1, 1970, 12:00 AM UTC"
310 );
311 assert_eq!(
312 human_utc_datetime_from_unix_secs(951_827_696),
313 "February 29, 2000, 12:34 PM UTC"
314 );
315 assert_eq!(
316 human_utc_datetime_from_unix_secs(13 * 3_600 + 5 * 60),
317 "January 1, 1970, 1:05 PM UTC"
318 );
319 }
320
321 #[test]
322 fn wrap_html5_keeps_generator_meta_without_visible_branding() {
323 let html = wrap_html5("<p>hi</p>", "Title", None, None, None, Some(0));
324
325 assert!(html.contains(&format!(
326 "<meta name=\"generator\" content=\"mdo {APP_VERSION}\">"
327 )));
328 assert!(!html.contains("Generated by"));
329 assert!(!html.contains("mdo-generated"));
330 }
331
332 #[test]
333 fn wrap_html5_shows_source_modified_time_with_machine_datetime() {
334 let html = wrap_html5("<p>hi</p>", "Title", None, None, None, Some(951_827_696));
335
336 assert!(html.contains(
337 "<footer class=\"mdo-source-meta\">Source modified: \
338 <time datetime=\"2000-02-29T12:34:56Z\">February 29, 2000, 12:34 PM UTC</time></footer>"
339 ));
340 }
341
342 #[test]
343 fn wrap_html5_renders_without_source_modified_time() {
344 let html = wrap_html5("<p>hi</p>", "Title", None, None, None, None);
345
346 assert!(html.contains("<main>\n<p>hi</p>\n</main>"));
347 assert!(!html.contains("Source modified"));
348 assert!(!html.contains("<footer"));
349 }
350
351 #[test]
352 fn wrapped_document_hides_theme_toggle_in_print() {
353 let html = wrap_html5("<p>hi</p>", "Title", None, None, None, None);
354
355 let fixed_position = html
356 .find("#theme-toggle{position:fixed")
357 .expect("toggle should be positioned on screen");
358 let print_hide = html
359 .find("@media print{#theme-toggle{display:none}}")
360 .expect("toggle should be hidden in print");
361
362 assert!(print_hide > fixed_position);
365 }
366
367 #[test]
368 fn wrapped_document_uses_compact_print_typography() {
369 let html = wrap_html5("<p>hi</p>", "Title", None, None, None, None);
370
371 let typography = html
372 .split_once("<style id=\"mdo-default-typography\">")
373 .expect("default typography block should be present")
374 .1
375 .split_once("</style>")
376 .expect("typography block should be closed")
377 .0;
378
379 assert!(typography.contains("@media print {"));
380 assert!(typography.contains("font-size: 11pt;"));
382 assert!(typography.contains("font-size: 20pt;"));
383 assert!(typography.contains("font-size: 1rem;"));
385 }
386
387 #[test]
388 fn wrapped_document_styles_alerts_in_light_and_dark_palettes() {
389 let html = wrap_html5("<p>hi</p>", "Title", None, None, None, None);
390
391 assert!(html.contains("\n:root{--alert-note:"));
394 assert!(html.contains("@media (prefers-color-scheme: dark){:root{--alert-note:"));
395 assert!(html.contains(":root[data-theme=\"light\"]{--alert-note:"));
397 assert!(html.contains(":root[data-theme=\"dark\"]{--alert-note:"));
398 for kind in ["note", "tip", "important", "warning", "caution"] {
399 assert!(html.contains(&format!("blockquote.markdown-alert-{kind}")));
400 }
401 }
402
403 #[test]
404 fn css_override_escapes_style_end_tags() {
405 let escaped = escape_style_end_tags("h1{} </STYLE><script>alert(1)</script>");
406
407 assert!(escaped.contains("<\\/style><script>"));
408 assert!(!escaped.to_ascii_lowercase().contains("</style><script>"));
409 }
410
411 }