aboutsummaryrefslogtreecommitdiff
path: root/code/src/markdown/mod.rs
blob: b6dfb55eeaf8372a79db22460560c5f01890b10c (plain)
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
use pest::{
    iterators::{Pair, Pairs},
    Parser,
};
use pest_derive::Parser;

use crate::html::escape;

#[derive(Parser)]
#[grammar = "grammar/markdown.pest"]
struct Grammar;

pub fn render(s: &str) -> String {
    match Grammar::parse(Rule::file, s) {
        Ok(pairs) => {
            eprintln!("{pairs:#?}");
            render_pairs(pairs)
        }
        Err(e) => panic!("{e}"),
    }
}

pub fn render_pairs(p: Pairs<Rule>) -> String {
    p.map(|p| render_ast(p)).collect::<Vec<_>>().join("")
}

pub fn render_ast(p: Pair<Rule>) -> String {
    match p.as_rule() {
        Rule::block => render_pairs(p.into_inner()),
        Rule::header => format!("<h1>{}</h1>", render_pairs(p.into_inner())),
        Rule::paragraph => format!("<p>{}</p>", render_pairs(p.into_inner())),
        Rule::list => format!("<ul>{}</ul>", render_pairs(p.into_inner())),
        Rule::list_item => format!("<li>{}</li>", render_pairs(p.into_inner())),
        Rule::span => render_pairs(p.into_inner()),
        Rule::text => escape(p.as_str()),
        Rule::EOI => "".to_string(),
        _ => todo!("{:?}", p.as_rule()),
    }
}