grace/htmlua

HTML Templating Engine

git clone https://git.gae.moe/grace/htmlua

gyoderAdded Basic HTTP stdlib4144fa2

httpstdlib
14.9 KiB416 linesraw
1use std::{cell::RefCell, fmt::Write, fs::read_to_string, path::PathBuf, rc::Rc};
2
3use anyhow::{Result, anyhow};
4use kuchikiki::{NodeRef, traits::TendrilSink};
5use mlua::{Lua, Table};
6use pulldown_cmark::{Options, Parser, html};
7use syntect::{
8    easy::HighlightLines,
9    highlighting::{Style, ThemeSet},
10    html::{IncludeBackground, styled_line_to_highlighted_html},
11    parsing::SyntaxSet,
12    util::LinesWithEndings,
13};
14
15use crate::{helpers::read_doc_from_file, htmlua_stdlib::create_htmlua_stdlib};
16
17
18
19pub fn execute_lua(document: NodeRef) -> Result<NodeRef> {
20    let lua = Lua::new();
21    let globals = lua.globals();
22
23    let stdout: Rc<RefCell<String>> = Rc::new(RefCell::new(String::new()));
24
25    let htmlua_table =
26        create_htmlua_stdlib(&lua, &stdout).map_err(|e| anyhow!("Failed to create Lua stdlib: {}", e))?;
27
28    globals
29        .set("htmlua", htmlua_table)
30        .map_err(|e| anyhow!("Failed to set global: {}", e))?;
31
32    let lua_elements: Vec<_> = match document.select("lua") {
33        Ok(e) => e.collect(),
34        Err(()) => return Err(anyhow!("Unable to find Lua")),
35    };
36
37    for node in lua_elements {
38        if let Some(text_node) = node.as_node().first_child() {
39            if let Some(lua_code) = text_node.as_text() {
40                stdout.borrow_mut().clear();
41                lua.load(lua_code.borrow().as_str())
42                    .exec()
43                    .map_err(|e| anyhow!("Failed to execute Lua: {}", e))?;
44                node.as_node()
45                    .insert_before(NodeRef::new_text(stdout.borrow().as_str()));
46                node.as_node().detach();
47            }
48        }
49    }
50
51    Ok(document)
52}
53
54pub fn process_markdown(document: NodeRef) -> Result<NodeRef> {
55    let markdown_elements: Vec<_> = match document.select("markdown") {
56        Ok(e) => e.collect(),
57        Err(()) => return Err(anyhow!("Unable to find markdown elements")),
58    };
59    for node in markdown_elements {
60        if let Some(text_node) = node.as_node().first_child() {
61            if let Some(markdown_text) = text_node.as_text() {
62                let borrowed_text = markdown_text.borrow();
63                let parser = Parser::new_ext(&borrowed_text, Options::all());
64                let mut html_output = String::new();
65                html::push_html(&mut html_output, parser);
66                let html_fragment = kuchikiki::parse_html().one(html_output);
67                for child in html_fragment.children() {
68                    node.as_node().insert_before(child);
69                }
70                // Remove the original markdown node.
71                node.as_node().detach();
72            }
73        }
74    }
75    Ok(document)
76}
77
78pub fn expand_template(document: NodeRef, component_path: &PathBuf, include_from: Option<&NodeRef>) -> Result<NodeRef> {
79    if let Some(from_node) = include_from {
80        for i in document
81            .select("includeelement")
82            .map_err(|()| anyhow!("Error finding includeelement"))?
83        {
84            if let Some(name) = i.attributes.borrow().get("name") {
85                let exported = from_node
86                    .select_first(format!("exportelement.{name}").as_str())
87                    .map_err(|()| anyhow!("Error finding exportelement"))?;
88                exported.as_node().children().rev().for_each(|c| i.as_node().insert_after(c));
89            }
90        }
91        while let Ok(i) = document.select_first("includeelement") {
92            i.as_node().detach();
93        }
94    }
95
96    for i in document
97        .select("include")
98        .map_err(|()| anyhow!("Error finding include"))?
99        .collect::<Vec<_>>()
100    {
101        let attrs = match i.as_node().as_element() {
102            Some(e) => e.attributes.borrow(),
103            None => continue,
104        };
105        if let Some(include_path) = attrs.get("path") {
106            let mut item_path = component_path.clone();
107            item_path.push(include_path);
108            let new_node = read_doc_from_file(item_path)?;
109            let replaced_node = expand_template(new_node, component_path, Some(i.as_node()))?;
110            replaced_node.select_first("html").map_err(|()| anyhow!("Error finding html"))?.as_node().children().rev().for_each(|c| i.as_node().insert_after(c));
111
112        }
113    }
114    while let Ok(i) = document.select_first("include") {
115        i.as_node().detach();
116    }
117    Ok(document)
118}
119
120pub fn process_syntax_highlighting(document: NodeRef) -> Result<NodeRef> {
121    let ps = SyntaxSet::load_defaults_newlines();
122    let mut ts = ThemeSet::load_defaults();
123    let syntax_elements: Vec<_> = match document.select("syntaxhighlight") {
124        Ok(e) => e.collect(),
125        Err(()) => return Err(anyhow!("Unable to find syntaxhighlight elements")),
126    };
127    if !syntax_elements.is_empty() {
128        // TODO: read from config
129        let themes = PathBuf::from("/var/www/htmlua/themes");
130        let _ = ts.add_from_folder(themes);
131    }
132    for node in syntax_elements {
133        let attrs = match node.as_node().as_element() {
134            Some(e) => e.attributes.borrow(),
135            None => continue,
136        };
137        let language = attrs.get("lang").unwrap_or("text");
138        let theme_name = attrs.get("theme").unwrap_or("base16-ocean.dark");
139        if let Some(text_node) = node.as_node().first_child() {
140            if let Some(code_text) = text_node.as_text() {
141                let syntax = ps
142                    .find_syntax_by_extension(language)
143                    .or_else(|| ps.find_syntax_by_name(language))
144                    .unwrap_or_else(|| ps.find_syntax_plain_text());
145                let theme = &ts.themes[theme_name];
146                let mut h = HighlightLines::new(syntax, theme);
147                let mut html_output = String::new();
148                write!(html_output, r#"<pre class="syntax-highlight" data-lang="{language}">"#)?;
149                html_output.push_str("<code>");
150                for line in LinesWithEndings::from(&code_text.borrow()) {
151                    let ranges: Vec<(Style, &str)> = h.highlight_line(line, &ps)?;
152                    let escaped = styled_line_to_highlighted_html(&ranges[..], IncludeBackground::No)?;
153                    html_output.push_str(&escaped);
154                }
155                html_output.push_str("</code></pre>");
156                let html_fragment = kuchikiki::parse_html().one(html_output);
157                for child in html_fragment.children() {
158                    node.as_node().insert_before(child);
159                }
160                // Remove the original syntaxhighlight node.
161                node.as_node().detach();
162            }
163        }
164    }
165    Ok(document)
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    #[test]
173    fn basic_lua() {
174        let page = r#"
175            <!DOCTYPE html>
176            <html>
177            <head>
178                <title>Basic HTML Page</title>
179            </head>
180            <body>
181                <h1>Hello World</h1>
182                <p>This is a paragraph.</p>
183                <span><lua>
184                    htmlua.println("Test from Lua!")
185                </lua></span>
186            </body>
187            </html>"#;
188        let document = kuchikiki::parse_html().one(page);
189        let d = execute_lua(document).unwrap();
190        let text = d.select_first("span").unwrap().as_node().text_contents();
191        assert_eq!(text, "Test from Lua!\n");
192        assert!(d.select_first("lua").is_err());
193    }
194
195    #[test]
196    fn multiple_lua() {
197        let page = r#"
198            <!DOCTYPE html>
199            <html>
200            <head>
201                <title>Basic HTML Page</title>
202            </head>
203            <body>
204                <h1>Hello World</h1>
205                <p>This is a paragraph.</p>
206                <span id="ta"><lua>
207                    htmlua.println("Test from Lua!")
208                </lua></span>
209                <div>
210                    <span id="tb"><lua>htmlua.println("test 2")</lua></span>
211                </div>
212            </body>
213            </html>"#;
214        let document = kuchikiki::parse_html().one(page);
215        let d = execute_lua(document).unwrap();
216        let text = d.select_first("#ta").unwrap().as_node().text_contents();
217        assert_eq!(text, "Test from Lua!\n");
218        let text = d.select_first("#tb").unwrap().as_node().text_contents();
219        assert_eq!(text, "test 2\n");
220        assert!(d.select_first("lua").is_err());
221    }
222
223    #[test]
224    fn basic_include() {
225        let page = r#"
226            <!DOCTYPE html>
227            <html>
228            <head>
229                <title>Basic HTML Page</title>
230            </head>
231            <body>
232                <h1>Hello World</h1>
233                <p>This is a paragraph.</p>
234                <include path="comp1.html" />
235                <span><lua>
236                    htmlua.println("Test from Lua!")
237                </lua></span>
238            </body>
239            </html>"#;
240        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
241        p.push("tests/components");
242        let document = kuchikiki::parse_html().one(page);
243        let d = expand_template(document, &p, None).unwrap();
244        let text = d.select_first("span").unwrap().as_node().text_contents();
245        assert_eq!(text, "included1");
246        assert!(d.select_first("include").is_err());
247    }
248
249    #[test]
250    fn multiple_include() {
251        let page = r#"
252            <!DOCTYPE html>
253            <html>
254            <head>
255                <title>Basic HTML Page</title>
256            </head>
257            <body>
258                <h1>Hello World</h1>
259                <p>This is a paragraph.</p>
260                <include path="multi1_1.html"></include>
261                <include path="multi1_2.html"></include>
262                <include path="multi1_3.html"></include>
263            </body>
264            </html>"#;
265        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
266        p.push("tests/components");
267        let document = kuchikiki::parse_html().one(page);
268        let d = expand_template(document, &p, None).unwrap();
269        let text = d.select_first("#inc1").unwrap().as_node().text_contents();
270        assert_eq!(text, "included1");
271        let text = d.select_first("#inc2").unwrap().as_node().text_contents();
272        assert_eq!(text, "included2");
273        let text = d.select_first("#inc3").unwrap().as_node().text_contents();
274        assert_eq!(text, "included3");
275        assert!(d.select_first("include").is_err());
276    }
277
278    #[test]
279    fn basic_lua_include() {
280        let page = r#"
281            <!DOCTYPE html>
282            <html>
283            <head>
284                <title>Basic HTML Page</title>
285            </head>
286            <body>
287                <h1>Hello World</h1>
288                <p>This is a paragraph.</p>
289                <span><lua>
290                    htmlua.println("Test from Lua!")
291                </lua></span>
292                <include path="comp1.html" />
293            </body>
294            </html>"#;
295        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
296        p.push("tests/components");
297        let document = kuchikiki::parse_html().one(page);
298        let d = execute_lua(expand_template(document, &p, None).unwrap()).unwrap();
299        let text = d.select_first("span").unwrap().as_node().text_contents();
300        println!("{}", d.to_string());
301        assert_eq!(text, "Test from Lua!\n");
302        assert!(d.select_first("lua").is_err());
303        let text = d.select_first("#inc1").unwrap().as_node().text_contents();
304        assert_eq!(text, "included1");
305        assert!(d.select_first("include").is_err());
306    }
307
308    #[test]
309    fn recursive_include() {
310        let page = r#"
311            <!DOCTYPE html>
312            <html>
313                <head>
314                    <title>Basic HTML Page</title>
315                </head>
316            <body>
317                <h1>Hello World</h1>
318                <include path="comp2_level1.html" />
319            </body>
320            </html>"#;
321        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
322        p.push("tests/components");
323        let document = kuchikiki::parse_html().one(page);
324        let d = expand_template(document, &p, None).unwrap();
325        let text = d.select_first("span").unwrap().as_node().text_contents();
326        assert_eq!(text, "included_twice");
327        assert!(d.select_first("include").is_err());
328    }
329
330    #[test]
331    fn export_element_include() {
332        let page = r#"
333            <!DOCTYPE html>
334            <html>
335                <head>
336                    <title>Basic HTML Page</title>
337                </head>
338            <body>
339                <h1>Hello World</h1>
340                <include path="with_include1.html">
341                    <exportelement class="el1"><span id="ta">element 1</span></exportelement>
342                    <exportelement class="el2"><span id="tb">element 2</span></exportelement>
343                </include>
344            </body>
345            </html>"#;
346        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
347        p.push("tests/components");
348        let document = kuchikiki::parse_html().one(page);
349        let d = expand_template(document, &p, None).unwrap();
350        let text = d.select_first("#ta").unwrap().as_node().text_contents();
351        assert_eq!(text, "element 1");
352        let text = d.select_first("#tb").unwrap().as_node().text_contents();
353        assert_eq!(text, "element 2");
354        assert!(d.select_first("exportelement").is_err());
355        assert!(d.select_first("includeelement").is_err());
356    }
357
358    #[test]
359    fn basic_markdown() {
360        let page = r"
361            <!DOCTYPE html>
362            <html>
363            <head>
364                <title>Markdown Test</title>
365            </head>
366            <body>
367                <h1>Hello World</h1>
368                <div>
369                    <markdown>
370# This is a heading
371This is a paragraph with **bold text** and *italic text*.
372
373- Item 1
374- Item 2
375- Item 3
376                    </markdown>
377                </div>
378            </body>
379            </html>";
380        let document = kuchikiki::parse_html().one(page);
381        let d = process_markdown(document).unwrap();
382        assert!(d.select_first("markdown").is_err());
383        assert!(d.select_first("p").is_ok());
384        assert!(d.select_first("ul").is_ok());
385    }
386
387    #[test]
388    fn basic_syntax_highlighting() {
389        let page = r#"
390            <!DOCTYPE html>
391            <html>
392            <head>
393                <title>Syntax Highlighting Test</title>
394            </head>
395            <body>
396                <h1>Code Example</h1>
397                <syntaxhighlight lang="rust">
398fn main() {
399    println!("Hello, world!");
400    let x = 42;
401    let y = "test";
402}
403                </syntaxhighlight>
404            </body>
405            </html>"#;
406        let document = kuchikiki::parse_html().one(page);
407        let d = process_syntax_highlighting(document).unwrap();
408        assert!(d.select_first("syntaxhighlight").is_err());
409        assert!(d.select_first("pre").is_ok());
410        assert!(d.select_first("code").is_ok());
411        let pre = d.select_first("pre").unwrap();
412        let attrs = pre.attributes.borrow();
413        assert_eq!(attrs.get("data-lang"), Some("rust"));
414        assert!(attrs.get("class").unwrap().contains("syntax-highlight"));
415    }
416}