Skip to main content

mdo_cli/
page.rs

1//! Page assembly: everything that turns an HTML fragment into the final
2//! HTML document - styles, scripts, and document wrapping.
3
4use 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
11// mdo keeps simple.css as the base stylesheet but softens the heading/body
12// scale for generated documents. Users who prefer the unmodified vendored
13// simple.css typography can pass assets/restore-simple-css.css with --css.
14const MDO_DEFAULT_TYPOGRAPHY_CSS: &str = include_str!("../assets/mdo-default-typography.css");
15
16// pulldown-cmark emits GFM alerts as blockquotes with a
17// `markdown-alert-{kind}` class. Keep the presentation in the generated
18// document so alerts also work for bare installs with no external assets.
19// The plain `:root` and prefers-color-scheme rules keep alerts styled when
20// JavaScript is disabled (the theme-toggle script never runs, so no
21// data-theme attribute is ever set); the higher-specificity
22// `:root[data-theme=...]` rules then follow the theme toggle rather than the
23// OS preference once a reader has selected a manual theme.
24const 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
33// ─── BEGIN THEME TOGGLE ────────────────────────────────────────────────
34// Self-contained light/dark mode toggle. To remove this feature entirely:
35//   1. Delete this block (down to "END THEME TOGGLE").
36//   2. Delete the `{theme_toggle}` line and `theme_toggle = ...` arg in
37//      `wrap_html5` below.
38// Variable values mirror simple.css's @media (prefers-color-scheme: dark).
39//
40// Behavior notes:
41// - OS theme is detected automatically and tracked live until the user makes
42//   a manual choice; the manual choice persists via localStorage.
43// - localStorage can throw on file:// pages in some browsers/configurations,
44//   so every access is wrapped \u2014 the toggle still works for the current page
45//   even when persistence is unavailable.
46// - An in-memory `manual` flag (not the localStorage read) is the source of
47//   truth for "the user made an explicit choice". It is initialized from the
48//   saved value and set on every toggle click regardless of whether
49//   localStorage.setItem succeeds, so a later prefers-color-scheme change
50//   can never clobber an explicit choice just because persistence failed
51//   (e.g. on file:// pages).
52// - The button is a real <button> (keyboard focusable/activatable) with a
53//   state-aware aria-label.
54// - This <style> block is emitted before the --css override block, so custom
55//   CSS can restyle or hide the toggle (e.g. `#theme-toggle{display:none}`)
56//   and reclaim the reserved narrow-screen padding (`body{padding-top:0}`).
57const 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"#;
101// ─── END THEME TOGGLE ──────────────────────────────────────────────────
102
103pub(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    // `<base href>` makes relative image/link refs in the rendered HTML resolve
112    // against the *source* directory even when the HTML lives elsewhere
113    // (e.g. when --open writes to %TEMP%). Must come before any element that
114    // references a URL, so we put it first inside <head>.
115    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    // Provenance lives only in <meta name="generator">; the visible page
134    // carries no mdo branding, version, or render timing (v0.6 quiet output).
135    let generator = format!("{APP_DISPLAY_NAME} {APP_VERSION}");
136    // Restrained source-freshness footer: the source file's filesystem
137    // modification time, rendered as UTC with a machine-readable datetime.
138    // The tiny inline script re-formats it in the reader's locale/timezone
139    // when JavaScript is available. Omitted entirely when the timestamp is
140    // missing or unreadable.
141    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, // ← THEME TOGGLE injection point (delete this line to remove)
181        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
229/// The source file's mtime as seconds since the Unix epoch, or `None` when
230/// the metadata is missing or unreadable (which must never block rendering).
231pub(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
239/// ISO 8601 UTC datetime, e.g. `2026-07-14T17:42:05Z`, for `<time datetime>`.
240fn 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
251/// Readable UTC fallback text, e.g. `July 14, 2026, 5:42 PM UTC`, shown when
252/// JavaScript cannot re-format the timestamp in the reader's locale.
253fn 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    // Howard Hinnant's civil-from-days algorithm, shifted for Unix epoch days.
272    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('&', "&amp;")
288        .replace('<', "&lt;")
289        .replace('>', "&gt;")
290        .replace('"', "&quot;")
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        // Midnight and noon exercise the 12-hour AM/PM edge cases.
307        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        // The print rule must come after the on-screen positioning rule in the
363        // same stylesheet, otherwise the fixed button would print on every page.
364        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        // Point sizes keep print type independent of the browser root font size.
381        assert!(typography.contains("font-size: 11pt;"));
382        assert!(typography.contains("font-size: 20pt;"));
383        // Screen sizes stay in rem, so the print rules cannot affect the screen.
384        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        // No-JS defaults: plain :root plus an OS dark-mode media query, so
392        // alerts stay styled when the theme-toggle script never runs.
393        assert!(html.contains("\n:root{--alert-note:"));
394        assert!(html.contains("@media (prefers-color-scheme: dark){:root{--alert-note:"));
395        // Manual theme-toggle overrides.
396        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    // Unix-rooted paths like `/home/user/...` are NOT absolute on Windows
412    // (no drive or UNC prefix), so `Url::from_directory_path` rejects them
413    // there — every test using such a path must be `#[cfg(unix)]`-gated or
414    // it panics under the Windows CI test job. Windows path forms get their
415    // own `#[cfg(windows)]` tests below.
416}