markdown-viewer-rs 0.4.0

Render a Markdown file with GitHub styling and live-reload it in your browser
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! Markdown → HTML rendering with GitHub-flavoured extensions and styling.

use std::fmt::Write as _;
use std::hash::{BuildHasher, Hasher};
use std::io::Read as _;
use std::sync::OnceLock;

use comrak::adapters::{CodefenceMeta, CodefenceRendererAdapter};
use comrak::plugins::syntect::{SyntectAdapter, SyntectAdapterBuilder};
use comrak::{Options, markdown_to_html_with_plugins, options::Plugins};

use crate::theme::{HL_PREFIX, base_css};
pub use crate::theme::{Style, Theme};

const LIVE_JS: &str = include_str!("../assets/live.js");
const UI_JS: &str = include_str!("../assets/ui.js");
const UI_CSS: &str = include_str!("../assets/ui.css");
const MERMAID_INIT_JS: &str = include_str!("../assets/mermaid-init.js");
/// mermaid.min.js, gzip-compressed to keep the binary small.
pub const MERMAID_JS_GZ: &[u8] = include_bytes!("../assets/mermaid.min.js.gz");
pub const MERMAID_VERSION: &str = include_str!("../assets/MERMAID_VERSION");
/// Where the server exposes mermaid.min.js.
pub const MERMAID_PATH: &str = "/__mdv/mermaid.js";
/// What a rendered ```mermaid block starts with.
const MERMAID_MARKER: &str = "<pre class=\"mermaid\"";

const MATH_INIT_JS: &str = include_str!("../assets/math-init.js");
pub const KATEX_JS: &str = include_str!("../assets/katex/katex.min.js");
/// katex.min.css with its fonts inlined as data URIs (generated by build.rs).
pub const KATEX_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/katex.css"));
pub const KATEX_VERSION: &str = include_str!("../assets/katex/VERSION");
pub const KATEX_JS_PATH: &str = "/__mdv/katex.js";
pub const KATEX_CSS_PATH: &str = "/__mdv/katex.css";
/// Every math form comrak emits carries this attribute.
const MATH_MARKER: &str = "data-math-style=";

/// Options that affect the surrounding HTML page, not the Markdown itself.
#[derive(Debug, Clone, Default)]
pub struct PageOptions {
    pub title: String,
    /// Initial theme; the viewer UI can switch it.
    pub theme: Theme,
    pub style: Style,
    /// Extra CSS appended after the built-in styles (`--css`).
    pub custom_css: Option<String>,
    /// Include the viewer UI: toolbar, contents/files sidebar, keyboard
    /// shortcuts, copy buttons (everything except `-o` exports and PDFs).
    pub ui: bool,
    /// For served pages: the document's path relative to the served root,
    /// used to subscribe to its live updates.
    pub doc: Option<String>,
    /// Sidebar to show initially: "contents", "files", or none.
    pub sidebar: Option<String>,
    /// Source line to scroll back to (the remembered reading position).
    pub resume_line: Option<u32>,
    /// The theme was given with `--theme`; a standalone page shouldn't
    /// replace it with one remembered in the browser.
    pub fixed_theme: bool,
    /// Number headings (1, 1.1, 1.2, …).
    pub number_headings: bool,
    /// The page is served by our HTTP server, so it can load extra
    /// resources (mermaid.js) from it instead of inlining them.
    pub served: bool,
    /// Include the live-reload script (requires `served`).
    pub live: bool,
    /// When the server stops, close the window instead of just showing a
    /// "stopped" banner (requires `live`).
    pub close_on_exit: bool,
    /// Optional `<base href>` so relative links resolve somewhere else
    /// (used when the page is written to a temp dir).
    pub base_href: Option<String>,
}

/// Reusable renderer. Building the syntax highlighter is relatively
/// expensive, so create one and keep it around.
pub struct Renderer {
    options: Options<'static>,
    render: RenderOptions,
    highlighter: SyntectAdapter,
    mermaid: MermaidAdapter,
}

/// How to treat YAML front matter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FrontMatter {
    /// Show it as a table, like GitHub.
    #[default]
    Table,
    /// Leave it out.
    Hide,
}

/// Options that change the rendered HTML itself.
#[derive(Debug, Clone, Default)]
pub struct RenderOptions {
    /// Tag elements with their source lines (`data-sourcepos`), for
    /// click-to-source and reading positions. Served pages only.
    pub sourcepos: bool,
    /// Obsidian notes: wiki links, embeds, callouts, highlights, comments.
    pub obsidian: bool,
    pub front_matter: FrontMatter,
}

/// Turns ```mermaid fences into `<pre class="mermaid">` blocks for
/// mermaid.js to draw in the browser (as GitHub does).
struct MermaidAdapter {
    sourcepos: bool,
}

impl CodefenceRendererAdapter for MermaidAdapter {
    fn write(
        &self,
        output: &mut dyn std::fmt::Write,
        fence: &CodefenceMeta<'_>,
    ) -> std::fmt::Result {
        let pos = match (self.sourcepos, fence.sourcepos) {
            (true, Some(sp)) => format!(" data-sourcepos=\"{sp}\""),
            _ => String::new(),
        };
        writeln!(
            output,
            "<pre class=\"mermaid\"{pos}>{}</pre>",
            escape_text(fence.code)
        )
    }
}

impl Default for Renderer {
    fn default() -> Self {
        Self::new()
    }
}

impl Renderer {
    pub fn new() -> Self {
        Self::with_options(RenderOptions::default())
    }

    pub fn with_options(render: RenderOptions) -> Self {
        let mut options = Options::default();
        let ext = &mut options.extension;
        ext.strikethrough = true;
        ext.table = true;
        ext.autolink = true;
        ext.tasklist = true;
        ext.footnotes = true;
        ext.alerts = true;
        ext.shortcodes = true;
        ext.header_id_prefix = Some(String::new());
        ext.front_matter_delimiter = Some("---".into());
        // Math as GitHub writes it: $…$, $$…$$ (inline or as a block),
        // $`…`$ and ```math fences.
        ext.math_dollars = true;
        ext.math_dollars_block = true;
        ext.math_code = true;
        options.render.github_pre_lang = true;
        options.render.tasklist_classes = true;
        // Raw HTML (e.g. `<p align="center"><img …></p>`) is common in READMEs.
        // Scripts are neutralised by the page's Content-Security-Policy instead.
        options.render.r#unsafe = true;
        options.render.sourcepos = render.sourcepos;
        if render.obsidian {
            let ext = &mut options.extension;
            ext.ofm_callouts = true;
            ext.wikilinks_title_after_pipe = true;
            // Embeds stay as text; obsidian.rs turns them into images.
            ext.wikilinks_ignore_embeds = true;
            ext.ofm_comments = true;
            ext.highlight = true;
        }

        let highlighter = SyntectAdapterBuilder::new()
            .css_with_class_prefix(HL_PREFIX)
            .build();

        Self {
            options,
            mermaid: MermaidAdapter {
                sourcepos: render.sourcepos,
            },
            render,
            highlighter,
        }
    }

    pub fn options(&self) -> &RenderOptions {
        &self.render
    }

    /// Render Markdown to an HTML fragment (the contents of `.markdown-body`).
    pub fn render_body(&self, markdown: &str) -> String {
        self.render_doc(markdown, None)
    }

    /// Render a document, resolving Obsidian links relative to `links`.
    pub fn render_doc(
        &self,
        markdown: &str,
        links: Option<&crate::obsidian::LinkContext>,
    ) -> String {
        let mut plugins = Plugins::default();
        plugins.render.codefence_syntax_highlighter = Some(&self.highlighter);
        plugins
            .render
            .codefence_renderers
            .insert("mermaid".into(), &self.mermaid);
        let mut html = crate::github::finish(markdown_to_html_with_plugins(
            markdown,
            &self.options,
            &plugins,
        ));
        if self.render.obsidian
            && let Some(ctx) = links
        {
            html = crate::obsidian::finish(html, ctx);
        }
        if self.render.front_matter == FrontMatter::Table
            && let Some((yaml, end)) = crate::frontmatter::extract(markdown)
        {
            html.insert_str(
                0,
                &crate::frontmatter::table(yaml, end, self.render.sourcepos),
            );
        }
        html
    }

    /// Render Markdown to a complete, self-contained HTML document.
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn render_page(&self, markdown: &str, page: &PageOptions) -> String {
        self.wrap_page(&self.render_body(markdown), page)
    }

    /// Wrap an already-rendered body fragment in a full HTML document.
    pub fn wrap_page(&self, body: &str, page: &PageOptions) -> String {
        let nonce = nonce();
        let mut out = String::with_capacity(body.len() + 64 * 1024);
        let theme = page.theme.as_str();
        let sidebar = escape_attr(page.sidebar.as_deref().unwrap_or(""));
        let fixed = if page.fixed_theme {
            " data-mdv-fixed-theme"
        } else {
            ""
        };
        let resume = page
            .resume_line
            .map(|l| format!(" data-mdv-resume=\"{l}\""))
            .unwrap_or_default();
        let numbering = match (page.number_headings, body.matches("<h1").count()) {
            (false, _) => "",
            // A single h1 is the title; number from h2 down.
            (true, 0 | 1) => " data-mdv-number=\"h2\"",
            (true, _) => " data-mdv-number=\"h1\"",
        };
        let _ = write!(
            out,
            "<!DOCTYPE html>\n<html lang=\"en\" data-mdv-theme=\"{theme}\" data-mdv-sidebar=\"{sidebar}\"{fixed}{resume}{numbering}>\n<head>\n<meta charset=\"utf-8\">\n"
        );
        out.push_str("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n");
        let _ = writeln!(
            out,
            "<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'self'; \
             img-src * data:; media-src *; style-src 'self' 'unsafe-inline'; font-src 'self' data:; \
             script-src 'nonce-{nonce}'; connect-src 'self'; object-src 'none'; frame-src 'none'\">"
        );
        if let Some(base) = &page.base_href {
            let _ = writeln!(out, "<base href=\"{}\">", escape_attr(base));
        }
        let _ = writeln!(out, "<title>{}</title>", escape_text(&page.title));
        out.push_str("<style>\n");
        out.push_str(base_css());
        out.push_str(page.style.css());
        if page.ui {
            out.push_str(UI_CSS);
        }
        let has_mermaid = body.contains(MERMAID_MARKER);
        let has_math = body.contains(MATH_MARKER);
        if has_math && !page.served {
            out.push_str(KATEX_CSS);
        }
        out.push_str("</style>\n");
        // User CSS goes last so it wins, in its own element so a stray
        // `</style>` in it can only end its own block.
        if let Some(css) = &page.custom_css {
            let _ = write!(out, "<style>\n{}\n</style>\n", css.replace("</", "<\\/"));
        }
        out.push_str("</head>\n<body>\n<article class=\"markdown-body\">\n");
        out.push_str(body);
        out.push_str("</article>\n");
        // The UI goes first so a remembered theme is applied before
        // diagrams are drawn.
        if page.ui {
            let doc = page.doc.as_deref().map(escape_attr).unwrap_or_default();
            let _ = write!(
                out,
                "<script nonce=\"{nonce}\" data-served=\"{}\" data-doc=\"{doc}\">\n{UI_JS}</script>\n",
                page.served
            );
        }
        // Math: same pattern as Mermaid below.
        if page.served {
            if page.live || has_math {
                let v = KATEX_VERSION.trim();
                let _ = write!(
                    out,
                    "<script nonce=\"{nonce}\" data-katex-js=\"{KATEX_JS_PATH}?v={v}\" \
                     data-katex-css=\"{KATEX_CSS_PATH}?v={v}\">\n{MATH_INIT_JS}</script>\n"
                );
            }
        } else if has_math {
            let _ = write!(
                out,
                "<script nonce=\"{nonce}\">\n{KATEX_JS}\n</script>\n<script nonce=\"{nonce}\">\n{MATH_INIT_JS}</script>\n"
            );
        }
        if page.served {
            // Live pages may gain a diagram later, so they always get the
            // (small) init script; it fetches mermaid.js only when needed.
            if page.live || has_mermaid {
                let _ = write!(
                    out,
                    "<script nonce=\"{nonce}\" data-mermaid-src=\"{MERMAID_PATH}?v={}\">\n{MERMAID_INIT_JS}</script>\n",
                    MERMAID_VERSION.trim()
                );
            }
        } else if has_mermaid {
            let _ = write!(
                out,
                "<script nonce=\"{nonce}\">\n{}\n</script>\n<script nonce=\"{nonce}\">\n{MERMAID_INIT_JS}</script>\n",
                mermaid_js()
            );
        }
        if page.live {
            let doc = page.doc.as_deref().map(escape_attr).unwrap_or_default();
            let _ = write!(
                out,
                "<script nonce=\"{nonce}\" data-close-on-exit=\"{}\" data-doc=\"{doc}\">\n{LIVE_JS}</script>\n",
                page.close_on_exit
            );
        }
        out.push_str("</body>\n</html>\n");
        out
    }
}

/// The decompressed mermaid.js, for inlining into standalone pages.
pub fn mermaid_js() -> &'static str {
    static JS: OnceLock<String> = OnceLock::new();
    JS.get_or_init(|| {
        let mut js = String::new();
        flate2::read::GzDecoder::new(MERMAID_JS_GZ)
            .read_to_string(&mut js)
            .expect("bundled mermaid.min.js.gz is valid");
        js
    })
}

/// A per-page random token for the CSP `script-src` nonce. Not
/// cryptographic, but unpredictable to the content of a Markdown file.
fn nonce() -> String {
    let mut h = std::collections::hash_map::RandomState::new().build_hasher();
    h.write_u128(
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or_default(),
    );
    format!("{:016x}", h.finish())
}

pub fn escape_text(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

pub fn escape_attr(s: &str) -> String {
    escape_text(s).replace('"', "&quot;")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn renders_gfm_features() {
        let r = Renderer::new();
        let html = r.render_body(
            "# Title\n\n~~gone~~ https://example.com\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n- [x] done\n\n> [!NOTE]\n> hi\n\n:smile:\n",
        );
        assert!(html.contains("<h1"), "{html}");
        assert!(html.contains("id=\"title\""), "{html}");
        assert!(html.contains("<del>gone</del>"), "{html}");
        assert!(html.contains("<a href=\"https://example.com\""), "{html}");
        assert!(html.contains("<table>"), "{html}");
        assert!(html.contains("type=\"checkbox\""), "{html}");
        assert!(html.contains("markdown-alert-note"), "{html}");
        assert!(html.contains('😄'), "{html}");
    }

    #[test]
    fn highlights_code_with_classes() {
        let r = Renderer::new();
        let html = r.render_body("```rust\nfn main() {}\n```\n");
        assert!(html.contains("hl-"), "{html}");
        assert!(html.contains("lang=\"rust\""), "{html}");
    }

    #[test]
    fn page_has_csp_and_nonce_matches() {
        let r = Renderer::new();
        let page = r.render_page(
            "<script>alert(1)</script>",
            &PageOptions {
                title: "<x>".into(),
                live: true,
                ..Default::default()
            },
        );
        assert!(page.contains("Content-Security-Policy"));
        assert!(page.contains("<title>&lt;x&gt;</title>"));
        let nonce = page
            .split("'nonce-")
            .nth(1)
            .and_then(|s| s.split('\'').next())
            .unwrap();
        assert!(page.contains(&format!(
            "<script nonce=\"{nonce}\" data-close-on-exit=\"false\" data-doc=\"\">"
        )));
    }

    #[test]
    fn mermaid_fence_becomes_diagram_block() {
        let r = Renderer::new();
        let html = r.render_body("```mermaid\ngraph TD\n  A-->B & C<D\n```\n");
        assert!(
            html.contains("<pre class=\"mermaid\">graph TD\n  A--&gt;B &amp; C&lt;D\n</pre>"),
            "{html}"
        );
    }

    #[test]
    fn standalone_page_inlines_mermaid_only_when_needed() {
        let r = Renderer::new();
        let opts = PageOptions::default();
        let plain = r.render_page("# hi", &opts);
        assert!(!plain.contains("<script"));
        let diagram = r.render_page("```mermaid\ngraph TD\nA-->B\n```", &opts);
        assert!(diagram.contains("globalThis[\"mermaid\"]"));
        assert!(diagram.contains("mdvEnhancers"));
    }

    #[test]
    fn served_page_loads_mermaid_from_server() {
        let r = Renderer::new();
        let opts = PageOptions {
            served: true,
            live: true,
            ..Default::default()
        };
        let page = r.render_page("# hi", &opts);
        assert!(page.contains("data-mermaid-src=\"/__mdv/mermaid.js?v="));
        assert!(!page.contains("globalThis[\"mermaid\"]"));
    }

    /// The bundle is inlined into a `<script>`; these sequences would end or
    /// confuse the element early. Guards against a future mermaid upgrade.
    #[test]
    fn mermaid_bundle_is_safe_to_inline() {
        let js = mermaid_js().to_ascii_lowercase();
        assert!(js.len() > 1_000_000);
        assert!(!js.contains("</script"));
        assert!(!js.contains("<script"));
    }

    #[test]
    fn renders_every_math_syntax() {
        let r = Renderer::new();
        let html = r.render_body(
            "Inline $a^2 + b^2$ and $`\\sqrt{x}`$.\n\n$$\n\\sum_{i=1}^n i\n$$\n\n```math\nE = mc^2\n```\n",
        );
        assert!(
            html.contains("<span data-math-style=\"inline\">a^2 + b^2</span>"),
            "{html}"
        );
        assert!(
            html.contains("<code data-math-style=\"inline\">\\sqrt{x}</code>"),
            "{html}"
        );
        assert!(html.contains("<div data-math-style=\"display\">"), "{html}");
        assert!(
            html.contains("<pre data-math-style=\"display\" lang=\"math\"><code>E = mc^2"),
            "{html}"
        );
    }

    #[test]
    fn dollar_amounts_are_not_math() {
        let r = Renderer::new();
        let html = r.render_body("It costs $5 and $10 is too much.\n");
        assert!(!html.contains("data-math-style"), "{html}");
    }

    #[test]
    fn standalone_page_inlines_katex_only_when_needed() {
        let r = Renderer::new();
        let opts = PageOptions::default();
        assert!(!r.render_page("# hi", &opts).contains("katex"));
        let page = r.render_page("$x$", &opts);
        assert!(page.contains("data:font/woff2;base64,"), "fonts inlined");
        assert!(!page.contains("url(fonts/"));
        assert!(page.contains("font-src 'self' data:"));
        assert!(page.contains(KATEX_JS));
    }

    #[test]
    fn served_page_loads_katex_from_server() {
        let r = Renderer::new();
        let opts = PageOptions {
            served: true,
            live: true,
            ..Default::default()
        };
        let page = r.render_page("# hi", &opts);
        assert!(page.contains("data-katex-js=\"/__mdv/katex.js?v="));
        assert!(!page.contains("data:font/woff2"));
    }

    #[test]
    fn katex_is_safe_to_inline() {
        for asset in [KATEX_JS, KATEX_CSS] {
            let lower = asset.to_ascii_lowercase();
            assert!(!lower.contains("</script") && !lower.contains("<script"));
            assert!(!lower.contains("</style"));
        }
    }
}