summaryrefslogtreecommitdiff
path: root/src/generate_html.rs
blob: dca68f7efb6c2e731f3d3d271a1036d1bc021f6b (plain) (blame)
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
use crate::*;

use markdown::*;
use recipe::*;


pub fn generate_html(document: &MarkdownDocument, page: &Page, website: &Website) -> String {
    let root = page.root();
    let page_name = sanitize_text(&page.name, true);
    let site_name = sanitize_text(&website.name, true);
    let mut parent_url = String::new();
    for segment in &page.parents {
        parent_url.push_str(&make_url_safe(segment)); parent_url.push('/');
    }
    parent_url.pop();

    let head = get_html_head(page, website); let head = head.trim();
    let home_link = format!("<a id='home' href='{root}index.html'>{site_name}</a>");
    let parent_link = match page.parents.last() {
        Some(name) => format!("<a id='parent' href='../{}.html'>{name}</a>", make_url_safe(name)),
        None => String::new(),
    };
    let table_of_contents = get_table_of_contents(page);
    let main = document_to_html(document, page, website); let main = main.trim();

    format!("\
<!DOCTYPE html>
<head>
<title>{page_name} &mdash; {site_name}</title>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
{head}
</head>
<body>
<header>
<nav id='up'>
{home_link}
{parent_link}
</nav>
<h1 id='title'>{page_name}</h1>
<nav id='toc'>
{table_of_contents}
</nav>
</header>
<main>
{main}
</main>
</body>
</html>")
}


pub fn generate_html_redirect(path: &str) -> String {
    let path = sanitize_text(path, false);
    format!("\
<!DOCTYPE html>
<head>
<title>Redirect</title>
<meta http-equiv='refresh' content='0; url={path}'>
</head>
<html>")
}


pub fn get_html_head(page: &Page, website: &Website) -> String {
    let root = page.root();
    website.get_config("html.head")
        .replace("href='/", &format!("href='{root}"))
        .replace("src='/", &format!("src='{root}"))
}


pub fn get_table_of_contents(page: &Page) -> String {
    if page.headings.iter().filter(|h| h.level != Level::Heading3).count() < 3 {
        return String::new();
    }
    let mut toc = String::from("<details><summary></summary><ul>\n");
    let site_name = sanitize_text(&page.name, true);
    toc.push_str(&format!("<li class='l1'><a href='#title'>{site_name}</a></li>\n"));

    for heading in &page.headings {
        let name = &heading.name;
        let url = &heading.url;
        let class = match heading.level {
            Level::Heading1 => "l1",
            Level::Heading2 => "l2",
            Level::Heading3 => "l3",
        };
        toc.push_str(&format!("<li class='{class}'><a href='#{url}'>{name}</a></li>\n"));
    }
    toc.push_str("</ul></details>\n");
    return toc;
}


pub fn document_to_html(document: &MarkdownDocument, page: &Page, website: &Website) -> String {
    let from = &page.name;
    let mut html = String::new();

    macro_rules! line_to_html {
        ($l:expr) => {{ line_to_html(&$l, page, website) }}; }
    macro_rules! html {
        ($($arg:tt)*) => {{ html.push_str(&format!($($arg)*)); html.push('\n'); }}; }
    macro_rules! tag {
        ($t:expr,$l:expr,$c:expr) => { html!("<{} {}>{}</{}>", $t, $c, line_to_html!($l), $t) };
        ($t:expr,$l:expr)         => { html!("<{}>{}</{}>",    $t,     line_to_html!($l), $t) }; }
    macro_rules! wrap {
        ($t:expr,$c:expr,$f:expr) => {{ html!("<{} {}>", $t, $c); $f; html!("</{}>", $t); }};
        ($t:expr,$f:expr)         => {{ html!("<{}>", $t);        $f; html!("</{}>", $t); }}; }

    let root = page.root();
    for block in &document.blocks {
        match block {
            Block::Heading { level, line } => {
                let id = make_url_safe(strip_appendix(&line_to_html!(line)));
                match level {
                    Level::Heading1 => tag!("h1", line, format!("id='{id}'")),
                    Level::Heading2 => tag!("h2", line, format!("id='{id}'")),
                    Level::Heading3 => tag!("h3", line, format!("id='{id}'")),
                }
            }
            Block::Paragraph(line) => tag!("p", line),
            Block::Math(content) => html!("<div class='math'>{}</div>", sanitize_text(content, false)),
            Block::List(lines) => wrap!("ul", for line in lines {
                // Insert a <br> tag directly after the first untagged colon.
                let mut depth = 0;
                let mut prev = '\0';
                let mut output = String::new();
                let mut class = String::new();
                for c in line_to_html!(line).chars() {
                    output.push(c);
                    if c == '<' {
                        depth += 1;
                    } else if c == '/' && prev == '<' {
                        depth -= 2;  // 2 because prev was a '<' as well.
                    } else if c == ':' && depth == 0 {
                        output.pop(); output.push_str("<br>");
                        class.push_str("extended"); depth += 99;
                    }
                    prev = c;
                }
                // Replace a leading checkbox with a real checkbox.
                if let Some(stripped) = output.strip_prefix("<code>[ ]</code>") {
                    output = format!("<input type='checkbox' disabled>{stripped}");
                    class.push_str(" checkbox");
                } else if let Some(stripped) = output.strip_prefix("<code>[x]</code>") {
                    output = format!("<input type='checkbox' disabled checked>{stripped}");
                    class.push_str(" checkbox");
                } else if let Some(stripped) = output.strip_prefix("<code>[X]</code>") {
                    output = format!("<input type='checkbox' disabled checked>{stripped}");
                    class.push_str(" checkbox");
                }else if let Some(stripped) = output.strip_prefix("[ ]") {
                    output = format!("<input type='checkbox' disabled>{stripped}");
                    class.push_str(" checkbox");
                } else if let Some(stripped) = output.strip_prefix("[x]") {
                    output = format!("<input type='checkbox' disabled checked>{stripped}");
                    class.push_str(" checkbox");
                } else if let Some(stripped) = output.strip_prefix("[X]") {
                    output = format!("<input type='checkbox' disabled checked>{stripped}");
                    class.push_str(" checkbox");
                }
                let class = class.trim();
                match class.is_empty() {
                    true => html!("<li>{output}</li>"),
                    false => html!("<li class='{class}'>{output}</li>"),
                }
            }),
            Block::Note(lines) => wrap!("aside", for line in lines { tag!("p", line) }),
            Block::Embed { label, path } => match path.rsplit_once('.') {
                Some((_, extension)) => {
                    let mut path = path.to_string();
                    if !path.contains("://") {
                        match website.has_static(page, &path) {
                            Some(resolved) => path = resolved,
                            None => warn!("Page {from:?} embeds nonexistent static file {path:?}"),
                        }
                    }
                    let label = sanitize_text(label, true);
                    match extension.to_lowercase().as_str() {
                        "jpg"|"jpeg"|"png"|"webp"|"gif"|"tiff" => html!(
                            "<figure><a href='{path}'><img src='{path}' alt='{label}' title='{label}' /></a></figure>"),
                        "mp3"|"wav"|"m4a" => html!("<audio controls src='{path}'>{label}</audio>"),
                        "mp4"|"avi" => html!("<video controls src='{path}'>{label}</video>"),
                        ext @ _ => warn!("Unrecognised extension for embedded file {path:?} with extension {ext:?} in page {from:?}"),
                    }
                }
                _ => warn!("Cannot embed file {path:?} with no file extension in page {from:?}"),
            }
            Block::Fragment { language, content } => {
                match language.as_str() {
                    "math" => html!("<div class='math'>{}</div>", content.replace("\n", " \\\\\n")),
                    "embed-html" => html!("{content}"),
                    "embed-css" => wrap!("style", html!("{content}")),
                    "embed-javascript"|"embed-js" => wrap!("script", html!("{content}")),
                    "hidden"|"todo"|"embed-html-head" => (),
                    "recipe" => {
                        let recipe = Recipe::parse(content);
                        html!("<div class='recipe'><ul>");
                        for ingredient in recipe.ingredients { html!("<li>{ingredient}</li>") }
                        html!("</ul><hr>");
                        for paragraph in recipe.process { html!("<p>{paragraph}</p>") }
                        html!("</div>");
                    },
                    "gallery" => wrap!("div", "class='gallery'", for line in content.lines() {
                        let file = line.trim();
                        if !website.has_image(file) {
                            warn!("Gallery on page {from:?} references nonexistent image {file:?}");
                            continue;
                        }
                        let large = format!("{root}images/large/{file}");
                        // let small = format!("{root}images/small/{file}");
                        let thumb = format!("{root}images/thumb/{file}");
                        html!("<a href='{large}'><img src='{thumb}' /></a>");
                    }),
                    "gallery-nav" => wrap!("div", "class='gallery-nav'", for line in content.lines() {
                        let line = line.trim();
                        if let Some((name, image)) = line.split_once("::") {
                            let name = name.trim();
                            let image = image.trim();
                            let ParsedLink { path, class, label } = parse_internal_link(name, page, website);
                            if website.has_image(image) {
                                let thumb = format!("{root}images/thumb/{image}");
                                html!("<a href='{path}' class='{class}'><img src='{thumb}'/><p>{label}</p></a>")
                            } else {
                                warn!("Gallery-nav on page {from:?} references nonexistent image {image:?}");
                            }
                        } else {
                            warn!("Gallery-nav on page {from:?} has line without a '::' separator");
                        }
                    }),
                    _ => {
                        html!("<pre class='{language}'>");
                        html!("{}", sanitize_text(content, false));
                        html!("</pre>");
                    },
                }
            }
            Block::Break => html!("<hr>"),
            Block::Table(table) => wrap!("div", "class='table'", wrap!("table", {
                wrap!("thead",
                    wrap!("tr", for column in &table.columns {
                        match column.border_right {
                            true => tag!("th", column.name, "class='border'"),
                            false => tag!("th", column.name),
                        }
                    })
                );
                for section in &table.sections {
                    wrap!("tbody", for row in section {
                        wrap!("tr", for (column, cell) in std::iter::zip(&table.columns, row) {
                            let text_raw = line_to_html!(cell);
                            let text = match text_raw.as_str() {
                                "Yes" => "✓",
                                "No"  => "✗",
                                other => other,
                            };
                            let mut class = match text {
                                "--" => "c",
                                _ => match column.alignment {
                                    Alignment::Left => "l",
                                    Alignment::Center => "c",
                                    Alignment::Right => "r",
                                },
                            }.to_string();
                            if ["No", "--", "0"].contains(&text_raw.as_str()) {
                                class.push_str(" dim");
                            };
                            if column.border_right {
                                class.push_str(" border");
                            }
                            html!("<td class='{class}'>{text}</td>");
                        })
                    })
                };
            }))
        }
    }
    return html;
}



fn line_to_html(line: &Line, page: &Page, website: &Website) -> String {
    let mut html = String::new();
    for line_element in &line.tokens {
        match line_element {
            Token::Normal(text) => {
                let text = &sanitize_text(text, true); html.push_str(text) }
            Token::Bold(text) => {
                let text = &sanitize_text(text, true); html.push_str(&format!("<b>{text}</b>")) }
            Token::Italic(text) => {
                let text = &sanitize_text(text, true); html.push_str(&format!("<i>{text}</i>")) }
            Token::Monospace(text) => {
                let text = &sanitize_text(text, false); html.push_str(&format!("<code>{text}</code>")) }
            Token::Math(text) => {
                let text = &sanitize_text(text, false); html.push_str(&format!("<span class='math'>{text}</span>")) }
            Token::InternalLink(name) => {
                let ParsedLink { path, class, label } = parse_internal_link(name, page, website);
                html.push_str(&format!("<a href='{path}' class='{class}'>{label}</a>"))
            }
            Token::ExternalLink { label, path } => {
                let ParsedLink { path, class, label } = parse_external_link(label, path, page, website);
                html.push_str(&format!("<a href='{path}' class='{class}'>{label}</a>"));
            }
        }
    }
    return html;
}



struct ParsedLink {
    pub path: String,
    pub label: String,
    pub class: &'static str,
}

fn parse_internal_link(name: &str, page: &Page, website: &Website) -> ParsedLink {
    let from = &page.name;
    let (class, label, path) = match name.split_once('#') {
        Some(("", heading)) => ("heading", heading, format!("#{}", strip_appendix(heading))),
        Some((page, heading)) => ("page", heading, format!("{page}.html#{}", strip_appendix(heading))),
        _ => ("page", name, format!("{name}.html")),
    };
    let mut path = make_url_safe(&path);
    let label = match label.rsplit_once('/') {
        Some((_, label)) => sanitize_text(label.trim(), true),
        None => sanitize_text(label.trim(), true),
    };
    // Check that the linked internal page exists.
    if class == "page" {
        match website.has_page(page, &path, "html") {
            Some(resolved) => path = resolved,
            None => warn!("Page {from:?} contains link to nonexistent page {path:?}"),
        }
    }
    // Check that the heading exists.
    if class == "heading" {
        let heading = path.strip_prefix('#').unwrap();
        if !page.headings.iter().any(|h| h.url == heading) {
            warn!("Page {from:?} contains link to nonexistent internal heading {heading:?}");
        }
    }
    ParsedLink { path, class, label }
}

fn parse_external_link(label: &str, path: &str, page: &Page, website: &Website) -> ParsedLink {
    let from = &page.name;
    let mut path = path.to_owned();
    let mut label = label.to_string();
    let mut is_internal = true;
    for protocol in ["mailto:", "http://", "https://"] {
        if let Some(stripped) = path.strip_prefix(protocol) {
            is_internal = false;
            if label.is_empty() {
                label = stripped.to_string();
            }
            break;
        }
    }
    if is_internal {
        // Check that the linked static file exists.
        match website.has_static(page, &path) {
            Some(resolved) => path = resolved,
            None => warn!("Page {from:?} contains link to nonexistent static file {path:?}"),
        }
        // Take the file name as the label if the link is unlabeled.
        if label.is_empty() {
            label = match path.rsplit_once('/') {
                Some((_, file)) => file.to_string(),
                None => path.clone(),
            };
        }
    }
    let label = sanitize_text(&label, true);
    ParsedLink { path, class: "external", label }
}


/// Replace each HTML-reserved character with an HTML-escaped character.
fn sanitize_text(text: &str, fancy: bool) -> String {
    let mut output = String::new();
    let chars: Vec<char> = text.chars().collect();
    for (i, c) in chars.iter().enumerate() {
        let prev = match i > 0 {
            true => chars[i - 1],
            false => ' ',
        };
        let next = match i + 1 < chars.len() {
            true => chars[i + 1],
            false => ' ',
        };
        match c {
            '&' => {
                // The HTML syntax for unicode characters is &#0000
                if let Some('#') = chars.get(i+1) { output.push(*c) }
                else { output.push_str("&amp;") }
            },
            '<' => output.push_str("&lt;"),
            '>' => output.push_str("&gt;"),
            '"' if fancy => match prev.is_whitespace() {
                true  => output.push('“'),
                false => output.push('”'),
            },
            '\'' if fancy => match prev.is_whitespace() {
                true  => output.push('‘'),
                false => output.push('’'),
            },
            '-' if fancy => match prev.is_whitespace() && next.is_whitespace() {
                true => output.push('—'),
                false => output.push('-'),
            }
            _ => output.push(*c),
        }
    }
    return output;
}


/// Remove a 'Appendix #: ' prefix from a string.
pub fn strip_appendix(text: &str) -> &str {
    if let Some((prefix, name)) = text.split_once(": ") {
        if prefix.starts_with("Appendix") {
            return name;
        }
    }
    return text;
}