wellington 0.0.1

A lightweight blogging engine using markdown and supporting sidenotes
Documentation
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
use pulldown_cmark::{Event, Tag, html, Parser};
use std::borrow::Cow;
use std::time::SystemTime;
use handlebars::{Handlebars, html_escape};

use sidenote_error::SidenoteError;
use toc::IndexedBlogPost;


pub struct SidenoteParser<'a> {
    parser: Parser<'a>,
    link_prefix: String,
    pub in_code_block: bool,
    pub in_sidenote_block: bool,
    pub remaining_text: String,
    pub title: &'a mut Option<String>,
    pub in_title: bool,
    pub in_image: bool,
    pub remaining_events: Vec<Event<'a>>,
    pub sidenotes: &'a mut Vec<String>
}



/// The main wrapper for pulldown_cmark events.
/// Wraps the events to account for sidenotes and custom
/// styling and html classes required for tufte-css.
/// Currently:
///
/// * checks text events for sidenotes, 
/// * checks code block tags, and remembers if we're in a 
/// code block, so as not to parse for sidenotes in that case
/// * returns the other events unchanged.
impl<'a> SidenoteParser<'a> {
    pub fn new(parser: Parser<'a>, 
               title: &'a mut Option<String>, 
               sidenotes: &'a mut Vec<String>) -> SidenoteParser<'a> {
        SidenoteParser{
            parser,
            title,
            link_prefix: "".to_string(),
            in_code_block: false,
            in_sidenote_block: false,
            remaining_text: String::from(""),
            in_title: false,
            in_image: false,
            remaining_events: vec![],
            sidenotes
        }
    }

    fn set_link_prefix(&mut self, link_prefix: String) {
        self.link_prefix = link_prefix;
    }

    fn parse_code_tag(&mut self, start: bool, on_success_return: Event<'a>) -> 
        Result<Event<'a>, SidenoteError> {
        if self.in_sidenote_block {
            Err(SidenoteError::NotMatched)
        } else {
            self.in_code_block = start;
            Ok(on_success_return)
        }
    }

    fn parse_paragraph_tag(&mut self, start: bool) -> 
        Event<'a> {
        if self.in_sidenote_block {
            if start {
                self.sidenotes.last_mut().unwrap().push_str("\n\n");
                Event::InlineHtml(Cow::from("<br /><br />\n"))
            } else { // create empty event
                Event::Text(Cow::from(""))
                // TODO: would be cleaner to instead skip this and go straight
                // to the next event and invoke self.next()
                // but to do this need to change all return types
            }
        } else {
            if start {
                Event::Start(Tag::Paragraph)
            } else {
                Event::End(Tag::Paragraph)
            }
        }
    }

    fn start_codeblock() -> Event<'a> {
        Event::InlineHtml(Cow::from("<pre class=\"code\"><code>"))
    }

    fn link_is_relative(link: &Cow<str>) -> bool {
        !(link.contains("://") || (link.chars().next() == Some('/')))
    }

    fn rewrite_link<'b>(&'a self, mut link: Cow<'b, str>) -> Cow<'b, str> {
        if SidenoteParser::link_is_relative(&link) {
            link.to_mut().insert_str(0, &self.link_prefix);
        }
        link
    }

    fn parse_next_event(&mut self, event: Event<'a>) -> 
        Result<Event<'a>, SidenoteError> {
        match event {
            Event::Text(text) => Ok(self.parse_text_block(text)),
            Event::Start(tag) => match tag {
                Tag::Code => self.parse_code_tag(true, Event::Start(Tag::Code)),
                Tag::CodeBlock(_lang) => self.parse_code_tag(true, 
                    SidenoteParser::start_codeblock()),
                Tag::Paragraph => Ok(self.parse_paragraph_tag(true)),
                Tag::Header(1) => {
                    self.in_title = true;
                    Ok(Event::Start(Tag::Header(1)))
                },
                Tag::Image(url, title) => {
                    self.in_image = true;
                    Ok(Event::Start(Tag::Image(self.rewrite_link(url), title)))
                },
                Tag::Link(link, title) => 
                    Ok(Event::Start(Tag::Link(self.rewrite_link(link), title))),
                _ => Ok(Event::Start(tag))
            },
            Event::End(tag) => match tag {
                Tag::Code => self.parse_code_tag(false, Event::End(Tag::Code)),
                Tag::CodeBlock(lang) => self.parse_code_tag(false, 
                    Event::End(Tag::CodeBlock(lang))),
                Tag::Paragraph => Ok(self.parse_paragraph_tag(false)),
                Tag::Header(1) => {
                    self.in_title = false;
                    Ok(Event::InlineHtml(Cow::from("</h1><section>")))
                },
                Tag::Image(url, title) => {
                    self.in_image = false;
                    Ok(Event::End(Tag::Image(url, title)))
                },
                Tag::Link(link, title) => 
                    Ok(Event::End(Tag::Link(link, title))),
                _ => Ok(Event::End(tag))
            },
            _ => Ok(event)
        }
    }
} 


impl<'a> Iterator for SidenoteParser<'a> {
    type Item = Result<Event<'a>, SidenoteError>;

    fn next(&mut self) -> Option<Result<Event<'a>, SidenoteError>> {
        match self.remaining_events.pop() {
            Some(e) => Some(Ok(e)),
            None => {
                if self.remaining_text.len() > 0 {
                    Some(self.parse_remaining_text())
                } else {
                    let next_event = self.parser.next();
                    match next_event {
                        Some(event) => Some(self.parse_next_event(event)),
                        None => None
                    }
                }
            }
        }
    }
} 


#[derive(Serialize)]
struct Sidenote {
    note: String
}

impl From<String> for Sidenote {
    fn from(note: String) -> Self {
        Sidenote{note}
    }
}


#[derive(Serialize)]
pub struct PostData<'a> {
    article: &'a str,
    title: Option<String>,
    first_published: SystemTime,
    last_updated: SystemTime,
    index_url: String,
    post_url: String,
    sidenotes: Vec<Sidenote>
}


impl<'a> PostData<'a> {

    pub fn new(article: &'a str) -> Self {
        PostData{
            article, title: None,
            first_published: SystemTime::now(),
            last_updated: SystemTime::now(),
            index_url: "/".to_string(),
            post_url: "/".to_string(),
            sidenotes: vec![]
        }
    }

    pub fn render(&self, template: &Handlebars) -> Result<String, SidenoteError> {
        match template.render("t1", &self) {
            Ok(s) => Ok(s),
            Err(e) => Err(SidenoteError::Template(
                format!("{:?}", e)))
        }
    }
}


impl<'a, 'b, 'c> From<(&'a str, 
                       &'b mut IndexedBlogPost, 
                       &'c str, 
                       String, 
                       Vec<String>)> for PostData<'a> {

    fn from(a: (&'a str, &'b mut IndexedBlogPost, &'c str, String, Vec<String>)) -> Self {
        PostData{
            article: a.0,
            first_published: a.1.first_published,
            last_updated: a.1.last_updated,
            index_url: a.2.to_string(),
            title: match a.1.title {
                Some(ref t) => Some(html_escape(t)),
                None => None
            },
            post_url: a.3,
            sidenotes: a.4.into_iter()
                .map(Sidenote::from)
                .collect()
        }
    }
}



pub struct ParsedMarkdown {
    pub html: String,
    pub title: Option<String>,
    pub sidenotes: Vec<String>
}


/// Main function to convert markdown to html
pub fn html_from_markdown(md: &str, link_prefix: String) -> Result<ParsedMarkdown, SidenoteError> {
    let mut title: Option<String> = None;
    let mut article = "<article>".to_string();
    let mut sidenotes: Vec<String> = vec![];
    {
        let mut parser = SidenoteParser::new(Parser::new(md), &mut title, &mut sidenotes);
        parser.set_link_prefix(link_prefix);
        for event in parser {
            html::push_html(&mut article, vec![event?].into_iter());
        }
    }

    article.push_str("</section></article>");

    let title = match title {
        Some(t) => match t.len() {
            0 => None,  // don't allow empty titles
            _ => Some(t)
        },
        None => None
    };

    Ok(ParsedMarkdown{html: article, title, sidenotes})

} 


#[cfg(test)]
mod tests {
    use std::borrow::Cow;
    use pulldown_cmark::Parser;
    use super::{html_from_markdown, SidenoteParser};

    #[test]
    fn check_catch_sidenote_errors() {
        let markdown_str = r#"
hello
=====

Here is some text with { badly formatted {sidenotes}.

* alpha
* beta

"#;

        let html_buf = html_from_markdown(markdown_str, "".to_string());
        assert!(html_buf.is_err());
    }

    #[test]
    fn check_fail_nested_code_sidenote() {

        let markdown_str = r#"
hello
=====

Here is some text with { a sidenote `and code nested`
    }"#;

        assert!(html_from_markdown(markdown_str, "".to_string()).is_err());
    }

    #[test]
    fn check_nested_sidenote_code() {
        let markdown_str = r#"
hello
=====

Here is some text with ` code {and curly braces nested`
"#;
        assert_eq!(html_from_markdown(markdown_str, "".to_string()).expect("Should succeed").html,
            r#"<article>
<h1>hello</h1><section>
<p>Here is some text with <code>code {and curly braces nested</code></p>
</section></article>"#);
    }


    #[test]
    fn check_multi_line_sidenotes() {
        let markdown_str = r#"
hello
=====

Here is some text with { a sidenote

spanning multiple lines, which is also supported

}.

* alpha
* beta

"#;

        let html_buf = html_from_markdown(markdown_str, "".to_string()).expect("Should succeed");

        assert_eq!(html_buf.sidenotes, vec![" a sidenote 

spanning multiple lines, which is also supported 

 "]);

        assert_eq!(
            html_buf.html,
            r#"<article>
<h1>hello</h1><section>
<p>Here is some text with <label class="sidenote-number"></label><span class="sidenote"> a sidenote<br /><br />
spanning multiple lines, which is also supported<br /><br />
</span>.</p>
<ul>
<li>alpha</li>
<li>beta</li>
</ul>
</section></article>"#
        );
    }

    #[test]
    fn check_to_markdown() {
        let markdown_str = r#"
hello
=====

Here is some text with {sidenotes} and {sidenotes}.

* alpha
* beta

And also some `inline_code` as well as

```
code_with{
    curly_braces();
}
```

"#;
        let html_buf = html_from_markdown(markdown_str, "".to_string()).expect("Shouldn't fail!");
        assert_eq!(html_buf.sidenotes, vec!["sidenotes ", "sidenotes "]);

        assert_eq!(
            html_buf.html,
            r#"<article>
<h1>hello</h1><section>
<p>Here is some text with <label class="sidenote-number"></label><span class="sidenote">sidenotes</span> and <label class="sidenote-number"></label><span class="sidenote">sidenotes</span>.</p>
<ul>
<li>alpha</li>
<li>beta</li>
</ul>
<p>And also some <code>inline_code</code> as well as</p>
<pre class="code"><code>code_with{
    curly_braces();
}
</code></pre>
</section></article>"#
        );
    }

    #[test]
    fn can_get_title() {
        let md = r#"
hello & hello
=====

Here is some text with {sidenotes}.
"#;
        let mut title: Option<String> = None;
        let mut sidenotes: Vec<String> = vec![];
        {
            let parser = SidenoteParser::new(Parser::new(md), &mut title, &mut sidenotes);
            for _ in parser {}
        }
        assert_eq!(title.expect("Should work, even with ampersands!"), "hello & hello")
    }

    #[test]
    fn can_parse_image() {
        let md = r#"
hello
=====

![image](https://image)
"#;
        assert_eq!(html_from_markdown(md, "".to_string()).expect("should work!").html, r#"<article>
<h1>hello</h1><section>
<p><img src="https://image" alt="" /><br /><span class="image-caption">image</span></p>
</section></article>"#);
    }

    #[test]
    fn check_absolute_links() {
        assert!(SidenoteParser::link_is_relative(&Cow::from("link.jpg")));
        assert!(SidenoteParser::link_is_relative(&Cow::from("etc/link.jpg")));
        assert!(!SidenoteParser::link_is_relative(&Cow::from("/etc/link.jpg")));
        assert!(!SidenoteParser::link_is_relative(&Cow::from("https://link.jpg")));
    }


    #[test]
    fn can_rewrite_links() {
        let md = r#"
hello
=====

[link](relative-link)

![image](https://image)

![image](relative-image.jpg)
"#;
        assert_eq!(html_from_markdown(md, "/prefix/".to_string()).expect("should work!").html, r#"<article>
<h1>hello</h1><section>
<p><a href="/prefix/relative-link">link</a></p>
<p><img src="https://image" alt="" /><br /><span class="image-caption">image</span></p>
<p><img src="/prefix/relative-image.jpg" alt="" /><br /><span class="image-caption">image</span></p>
</section></article>"#);
    }
}