aboutsummaryrefslogtreecommitdiff
path: root/src/convert/html.rs
blob: 57749542c2f2d858186ae85c39493b37ec0f9fd7 (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
use {crate::ast::Node, std::fmt::Write};

pub fn convert(source: &[Node]) -> String {
  let mut html = String::new();

  // Since we have an AST tree of the Gemtext, it is very easy to convert from
  // this AST tree to an alternative markup format.
  for node in source {
    match node {
      Node::Text(text) => {
        let _ = write!(&mut html, "<p>{text}</p>");
      }
      Node::Link { to, text } => {
        let _ = write!(
          &mut html,
          "<a href=\"{}\">{}</a><br>",
          to,
          text.clone().unwrap_or_else(|| to.clone())
        );
      }
      Node::Heading { level, text } => {
        let _ = write!(
          &mut html,
          "<{}>{}</{0}>",
          match level {
            1 => "h1",
            2 => "h2",
            3 => "h3",
            _ => "p",
          },
          text
        );
      }
      Node::List(items) => {
        let _ = write!(&mut html, "<ul>");

        for item in items {
          let _ = write!(&mut html, "<li>{item}</li>");
        }

        let _ = write!(&mut html, "</ul>");
      }
      Node::Blockquote(text) => {
        let _ = write!(&mut html, "<blockquote>{text}</blockquote>");
      }
      Node::PreformattedText { text, .. } => {
        let _ = write!(&mut html, "<pre>{text}</pre>");
      }
      Node::Whitespace => {}
    }
  }

  html
}