aboutsummaryrefslogtreecommitdiff
path: root/src/template.rs
blob: 03325063a94e45f5fe291f7396e17ac32c1879c0 (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
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
use std::collections::HashMap;
use std::fs::File;
use std::path::PathBuf;
use std::io::Read;

const TXT_TEMPLATE: &'static str = include_str!("../templates/index.txt");
const HTML_TEMPLATE: &'static str = include_str!("../templates/index.html");
const GMI_TEMPLATE: &'static str = include_str!("../templates/index.gmi");
const RSS_TEMPLATE: &'static str = include_str!("../templates/feed.xml");

// Parse and Render

pub enum Token {
    Text(String),
    DisplayDirective { content: String },
    ConditionalDirective { condition: String, children: Vec<Token>},
    IteratorDirective { collection: String, member_label: String, children: Vec<Token> }
}

impl std::fmt::Display for Token {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Token::Text(label) => write!(f, "Text {}", label),
            Token::DisplayDirective{content} => write!(f, "DisplayDirective {}", content),
            Token::ConditionalDirective{condition, children} => {
                write!(f, "ConditionalDirective {} [[[\n", condition)?;
                for child in children {
                    write!(f, "\t{}\n", child)?;
                }
                write!(f, "\n]]]")
            },
            Token::IteratorDirective{collection, member_label, children} => {
                write!(f, "{} in {}\n", collection, member_label)?;
                for child in children {
                    write!(f, "\t{}\n", child)?;
                }
                write!(f, "\n]]]")
            },
        }
    }
}

#[derive(Clone)]
pub enum TemplateValue {
    String(String),
    Unsigned(u64),
    Bool(bool),
    Collection(Vec<TemplateContext>),
    Context(TemplateContext)
}

impl TemplateValue {
    fn render(&self) -> String {
        match self {
            TemplateValue::String(string) => string.to_string(),
            TemplateValue::Unsigned(number) => format!("{}", number),
            TemplateValue::Bool(bool) => format!("{}", bool),
            _ => "".to_string()
        }
    }
}

pub type TemplateContext = HashMap<String, TemplateValue>;

struct TemplateContextGetter {}
impl TemplateContextGetter {
    fn get(context: &TemplateContext, path: &str) -> Option<TemplateValue> {
        let path_parts: Vec<&str> = path.split('.').collect();
        TemplateContextGetter::recursively_get_value(context, &path_parts)
    }

    fn recursively_get_value(context: &TemplateContext, path: &[&str]) -> Option<TemplateValue> {
        match context.get(path[0]) {
            Some(TemplateValue::Context(next)) if path.len() > 1 => TemplateContextGetter::recursively_get_value(next, &path[1..]),
            Some(value) if path.len() == 1 => Some(value.clone()),
            _ => None
        }
    }
}

pub struct ParsedTemplate {
    pub tokens: Vec<Token>
}

impl ParsedTemplate {
    pub fn render(&self, context: &TemplateContext) -> String {
        ParsedTemplate::render_tokens(&self.tokens, context)
    }

    pub fn render_tokens(tokens: &Vec<Token>, context: &TemplateContext) -> String {
        let mut rendered_template: String = String::new();
        for token in tokens {
            match token {
                Token::Text(contents) => rendered_template.push_str(&contents),
                Token::DisplayDirective { content } => {
                    match TemplateContextGetter::get(context, &content) {
                        Some(value) => rendered_template.push_str(&value.render()),
                        None => panic!("{} is not a valid key", content)
                    }
                },
                Token::ConditionalDirective { condition, children} => {
                    let mut negator = false;
                    let mut condition = condition.to_string();
                    if condition.starts_with('!') {
                        negator = true;
                        condition = condition[1..].to_string();
                    }
                    match TemplateContextGetter::get(context, &condition) {
                        Some(TemplateValue::Bool(value)) => {
                            if negator ^ value {
                                rendered_template.push_str(&ParsedTemplate::render_tokens(children, context))
                            }
                        },
                        _ => panic!("{} is not a boolean value", condition)
                    }
                },
                Token::IteratorDirective { collection, member_label, children } => {
                    match TemplateContextGetter::get(context, &collection) {
                        Some(TemplateValue::Collection(collection)) => {
                            for member in collection {
                                let mut child_context = context.clone();
                                child_context.insert(
                                    member_label.to_string(),
                                    TemplateValue::Context(member)
                                );
                                rendered_template.push_str(&ParsedTemplate::render_tokens(&children, &child_context))
                            }
                        },
                        _ => panic!("{} is not a collection", collection)
                    }
                }
            }
        }
        rendered_template
    }
}

pub fn parse(template: &str) -> ParsedTemplate {
    let mut tokens = Vec::new();
    tokenize(template, &mut tokens);
    ParsedTemplate {
        tokens
    }
}

fn tokenize(template: &str, tokens: &mut Vec<Token>) {
    let mut remaining_template = template;

    while !remaining_template.is_empty() && remaining_template.contains("{{") {
        let directive_start_index = remaining_template.find("{{")
            .expect("Was expecting at least one tag opener");
        if directive_start_index > 0 {
            let text = remaining_template[..directive_start_index].to_string();
            tokens.push(Token::Text(text.to_string()));
        }
        remaining_template = &remaining_template[directive_start_index..];

        let directive_end_index = remaining_template.find("}}")
            .expect("Was expecting }} after {{") + 2;
        let directive = &remaining_template[..directive_end_index];
        remaining_template = &remaining_template[directive_end_index..];

        let directive_type = directive.chars().nth(2).unwrap();
        match directive_type {
            // Simple Directives
            '=' => {
                let content = directive[3..directive.len() - 2].trim();
                tokens.push(Token::DisplayDirective{
                    content: content.to_string()
                });
            },
            // Block Directives
            '?' | '~' => {
                let content = directive[3..directive.len() - 2].trim();
                let mut children = Vec::new();

                match directive_type {
                    '?' => {
                        let closing_block = remaining_template.find("{{?}}").unwrap();
                        let directive_block = &remaining_template[..closing_block];
                        remaining_template = &remaining_template[closing_block + 5..];
                        tokenize(directive_block, &mut children);
                        tokens.push(Token::ConditionalDirective{
                            condition: content.to_string(),
                            children
                        });
                    },
                    '~' => {
                        let parts: Vec<_> = content.splitn(2, ':').collect();
                        let closing_block = remaining_template.find("{{~}}").unwrap();
                        let directive_block = &remaining_template[..closing_block];
                        remaining_template = &remaining_template[closing_block + 5..];
                        tokenize(directive_block, &mut children);
                        if parts.len() == 2 {
                            tokens.push(Token::IteratorDirective {
                                collection: parts[0].trim().to_string(),
                                member_label: parts[1].trim().to_string(),
                                children
                            });
                        }
                    },
                    _ => unreachable!()
                }
            },
            _ => unreachable!()
        }
    }
    tokens.push(Token::Text(remaining_template.to_string()));
}

// File helpers.

pub fn find(template_directory: &PathBuf, filename: &str) -> Option<String> {
    let template_path = template_directory.join(filename);
    if template_path.exists() {
        let mut contents = String::new();
        if File::open(template_path).ok()?.read_to_string(&mut contents).is_ok() {
            return Some(contents);
        }
    }
    find_default(filename)
}

fn find_default(filename: &str) -> Option<String> {
    match filename {
        "index.txt" => Some(TXT_TEMPLATE.to_string()),
        "index.html" => Some(HTML_TEMPLATE.to_string()),
        "index.gmi" => Some(GMI_TEMPLATE.to_string()),
        "index.rss" => Some(RSS_TEMPLATE.to_string()),
        &_ => None
    }
}