grace/htmlua

HTML Templating Engine

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

gyoderfixed parser bugbfa5d30

render_fixes
23.7 KiB670 linesraw
1use std::{
2    cell::{LazyCell, RefCell},
3    fmt::Write,
4    path::PathBuf,
5    rc::Rc,
6};
7
8use anyhow::{Result, anyhow};
9use kuchikiki::{NodeRef, traits::TendrilSink};
10use markup5ever::{LocalName, Namespace, QualName};
11use mlua::Lua;
12use pulldown_cmark::{Options, Parser, html};
13use syntect::{
14    easy::HighlightLines,
15    highlighting::{Style, ThemeSet},
16    html::{IncludeBackground, styled_line_to_highlighted_html},
17    parsing::SyntaxSet,
18    util::LinesWithEndings,
19};
20
21use crate::{helpers::read_doc_from_file, htmlua_stdlib::create_htmlua_stdlib, serve::get_config};
22
23
24fn build_lua_with_stdout(stdout: &Rc<RefCell<String>>) -> Result<Lua> {
25    let lua = Lua::new();
26    let globals = lua.globals();
27
28    let htmlua_table = create_htmlua_stdlib(&lua, stdout).map_err(|e| anyhow!("Failed to create Lua stdlib: {}", e))?;
29
30    globals
31        .set("htmlua", htmlua_table)
32        .map_err(|e| anyhow!("Failed to set global: {}", e))?;
33
34    Ok(lua)
35}
36
37pub fn execute_lua(document: NodeRef) -> Result<NodeRef> {
38    let stdout: Rc<RefCell<String>> = Rc::new(RefCell::new(String::new()));
39    let lua = LazyCell::new(|| build_lua_with_stdout(&stdout).unwrap_or_default());
40    let lua_elements: Vec<_> = match document.select("lua") {
41        Ok(e) => e.collect(),
42        Err(()) => return Err(anyhow!("Unable to find Lua")),
43    };
44
45    for node in lua_elements {
46        if let Some(text_node) = node.as_node().first_child() {
47            if let Some(lua_code) = text_node.as_text() {
48                stdout.borrow_mut().clear();
49                lua.load(lua_code.borrow().as_str())
50                    .exec()
51                    .map_err(|e| anyhow!("Failed to execute Lua: {}", e))?;
52                node.as_node()
53                    .insert_before(NodeRef::new_text(stdout.borrow().as_str()));
54                node.as_node().detach();
55            }
56        }
57    }
58
59    Ok(document)
60}
61
62pub fn process_markdown(document: NodeRef) -> Result<NodeRef> {
63    let markdown_elements: Vec<_> = match document.select("markdown") {
64        Ok(e) => e.collect(),
65        Err(()) => return Err(anyhow!("Unable to find markdown elements")),
66    };
67    for node in markdown_elements {
68        if let Some(text_node) = node.as_node().first_child() {
69            if let Some(markdown_text) = text_node.as_text() {
70                let borrowed_text = markdown_text.borrow();
71                let parser = Parser::new_ext(&borrowed_text, Options::all());
72                let mut html_output = String::new();
73                html::push_html(&mut html_output, parser);
74                let html_fragment = kuchikiki::parse_html().one(html_output);
75                for child in html_fragment.children() {
76                    node.as_node().insert_before(child);
77                }
78                // Remove the original markdown node.
79                node.as_node().detach();
80            }
81        }
82    }
83    Ok(document)
84}
85
86pub fn expand_template(document: NodeRef, component_path: &PathBuf, include_from: Option<&NodeRef>) -> Result<NodeRef> {
87    if let Some(from_node) = include_from {
88        for i in document
89            .select("includeelement")
90            .map_err(|()| anyhow!("Error finding includeelement"))?
91        {
92            if let Some(name) = i.attributes.borrow().get("name") {
93                let exported = from_node
94                    .select_first(format!("exportelement.{name}").as_str())
95                    .map_err(|()| anyhow!("Error finding exportelement"))?;
96                exported
97                    .as_node()
98                    .children()
99                    .rev()
100                    .for_each(|c| i.as_node().insert_after(c));
101            }
102        }
103        while let Ok(i) = document.select_first("includeelement") {
104            i.as_node().detach();
105        }
106    }
107
108    for i in document
109        .select("include")
110        .map_err(|()| anyhow!("Error finding include"))?
111        .collect::<Vec<_>>()
112    {
113        let attrs = match i.as_node().as_element() {
114            Some(e) => e.attributes.borrow(),
115            None => continue,
116        };
117        if let Some(include_path) = attrs.get("path") {
118            let mut item_path = component_path.clone();
119            item_path.push(include_path);
120            let new_node = read_doc_from_file(item_path)?;
121            let replaced_node = expand_template(new_node, component_path, Some(i.as_node()))?;
122            replaced_node
123                .select_first("html")
124                .map_err(|()| anyhow!("Error finding html"))?
125                .as_node()
126                .children()
127                .rev()
128                .for_each(|c| i.as_node().insert_after(c));
129        }
130    }
131    while let Ok(i) = document.select_first("include") {
132        i.as_node().detach();
133    }
134    Ok(document)
135}
136
137pub fn process_syntax_highlighting(document: NodeRef) -> Result<NodeRef> {
138    let config = get_config();
139    let ps = SyntaxSet::load_defaults_newlines();
140    let mut ts = ThemeSet::load_defaults();
141    let syntax_elements: Vec<_> = match document.select("syntaxhighlight") {
142        Ok(e) => e.collect(),
143        Err(()) => return Err(anyhow!("Unable to find syntaxhighlight elements")),
144    };
145    if !syntax_elements.is_empty() && config.syntax_highlighting.load_custom_themes {
146        let _ = ts.add_from_folder(&config.paths.themes);
147    }
148    for node in syntax_elements {
149        let attrs = match node.as_node().as_element() {
150            Some(e) => e.attributes.borrow(),
151            None => continue,
152        };
153        let language = attrs.get("lang").unwrap_or("text");
154        let theme_name = attrs.get("theme").unwrap_or(&config.syntax_highlighting.default_theme);
155        if let Some(text_node) = node.as_node().first_child() {
156            if let Some(code_text) = text_node.as_text() {
157                let syntax = ps
158                    .find_syntax_by_extension(language)
159                    .or_else(|| ps.find_syntax_by_name(language))
160                    .unwrap_or_else(|| ps.find_syntax_plain_text());
161                let theme = &ts.themes[theme_name];
162                let mut h = HighlightLines::new(syntax, theme);
163                let mut html_output = String::new();
164                write!(html_output, r#"<pre class="syntax-highlight" data-lang="{language}">"#)?;
165                html_output.push_str("<code>");
166                for line in LinesWithEndings::from(&code_text.borrow()) {
167                    let ranges: Vec<(Style, &str)> = h.highlight_line(line, &ps)?;
168                    let escaped = styled_line_to_highlighted_html(&ranges[..], IncludeBackground::No)?;
169                    html_output.push_str(&escaped);
170                }
171                html_output.push_str("</code></pre>");
172                let html_fragment = kuchikiki::parse_html().one(html_output);
173                for child in html_fragment.children() {
174                    node.as_node().insert_before(child);
175                }
176                // Remove the original syntaxhighlight node.
177                node.as_node().detach();
178            }
179        }
180    }
181    Ok(document)
182}
183
184pub fn generate_footnotes(document: NodeRef) -> Result<NodeRef> {
185    let Ok(footnote_container) = document.select_first("footnotecontainer") else {
186        return Ok(document);
187    };
188
189    let ctx_name = QualName::new(None, Namespace::from("http://www.w3.org/1999/xhtml"), LocalName::from("div"));
190    for (i, footnote) in document
191        .select("footnote")
192        .map_err(|()| anyhow!("Failed to get footnote"))?
193        .enumerate()
194    {
195        let i = i + 1;
196        let fn_text = footnote.text_contents();
197        let sup_tag = kuchikiki::parse_fragment(ctx_name.clone(), Vec::new())
198            .one(format!("<a href=#ft-text-{i}><sup id=\"ft-sup-{i}\" title=\"{fn_text}\">{i}</sup></a>"))
199            .select_first("a")
200            .map_err(|()| anyhow!("parse err"))?;
201        footnote.as_node().insert_after(sup_tag.as_node().clone());
202        let text_tag = kuchikiki::parse_fragment(ctx_name.clone(), Vec::new())
203            .one(format!("<p id=\"ft-text-{i}\"><a href=#ft-sup-{i}>{i}:</a> {fn_text}</p>"))
204            .select_first("p")
205            .map_err(|()| anyhow!("parse err"))?;
206        footnote_container.as_node().insert_before(text_tag.as_node().clone());
207    }
208    while let Ok(i) = document.select_first("footnote") {
209        i.as_node().detach();
210    }
211    footnote_container.as_node().detach();
212    Ok(document)
213}
214
215#[cfg(test)]
216mod tests {
217    use httptest::{Expectation, ServerPool, matchers::*, responders::*};
218    use markup5ever::{namespace_url, ns};
219
220    use super::*;
221
222    #[test]
223    fn basic_lua() {
224        let page = r#"
225            <!DOCTYPE html>
226            <html>
227            <head>
228                <title>Basic HTML Page</title>
229            </head>
230            <body>
231                <h1>Hello World</h1>
232                <p>This is a paragraph.</p>
233                <span><lua>
234                    htmlua.println("Test from Lua!")
235                </lua></span>
236            </body>
237            </html>"#;
238        let document = kuchikiki::parse_html().one(page);
239        let d = execute_lua(document).unwrap();
240        let text = d.select_first("span").unwrap().as_node().text_contents();
241        assert_eq!(text, "Test from Lua!\n");
242        assert!(d.select_first("lua").is_err());
243    }
244
245    #[test]
246    fn multiple_lua() {
247        let page = r#"
248            <!DOCTYPE html>
249            <html>
250            <head>
251                <title>Basic HTML Page</title>
252            </head>
253            <body>
254                <h1>Hello World</h1>
255                <p>This is a paragraph.</p>
256                <span id="ta"><lua>
257                    htmlua.println("Test from Lua!")
258                </lua></span>
259                <div>
260                    <span id="tb"><lua>htmlua.println("test 2")</lua></span>
261                </div>
262            </body>
263            </html>"#;
264        let document = kuchikiki::parse_html().one(page);
265        let d = execute_lua(document).unwrap();
266        let text = d.select_first("#ta").unwrap().as_node().text_contents();
267        assert_eq!(text, "Test from Lua!\n");
268        let text = d.select_first("#tb").unwrap().as_node().text_contents();
269        assert_eq!(text, "test 2\n");
270        assert!(d.select_first("lua").is_err());
271    }
272
273    #[test]
274    fn basic_include() {
275        let page = r#"
276            <!DOCTYPE html>
277            <html>
278            <head>
279                <title>Basic HTML Page</title>
280            </head>
281            <body>
282                <h1>Hello World</h1>
283                <p>This is a paragraph.</p>
284                <include path="comp1.html" />
285                <span><lua>
286                    htmlua.println("Test from Lua!")
287                </lua></span>
288            </body>
289            </html>"#;
290        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
291        p.push("tests/components");
292        let document = kuchikiki::parse_html().one(page);
293        let d = expand_template(document, &p, None).unwrap();
294        let text = d.select_first("span").unwrap().as_node().text_contents();
295        assert_eq!(text, "included1");
296        assert!(d.select_first("include").is_err());
297    }
298
299    #[test]
300    fn multiple_include() {
301        let page = r#"
302            <!DOCTYPE html>
303            <html>
304            <head>
305                <title>Basic HTML Page</title>
306            </head>
307            <body>
308                <h1>Hello World</h1>
309                <p>This is a paragraph.</p>
310                <include path="multi1_1.html"></include>
311                <include path="multi1_2.html"></include>
312                <include path="multi1_3.html"></include>
313            </body>
314            </html>"#;
315        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
316        p.push("tests/components");
317        let document = kuchikiki::parse_html().one(page);
318        let d = expand_template(document, &p, None).unwrap();
319        let text = d.select_first("#inc1").unwrap().as_node().text_contents();
320        assert_eq!(text, "included1");
321        let text = d.select_first("#inc2").unwrap().as_node().text_contents();
322        assert_eq!(text, "included2");
323        let text = d.select_first("#inc3").unwrap().as_node().text_contents();
324        assert_eq!(text, "included3");
325        assert!(d.select_first("include").is_err());
326    }
327
328    #[test]
329    fn basic_lua_include() {
330        let page = r#"
331            <!DOCTYPE html>
332            <html>
333            <head>
334                <title>Basic HTML Page</title>
335            </head>
336            <body>
337                <h1>Hello World</h1>
338                <p>This is a paragraph.</p>
339                <span><lua>
340                    htmlua.println("Test from Lua!")
341                </lua></span>
342                <include path="comp1.html" />
343            </body>
344            </html>"#;
345        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
346        p.push("tests/components");
347        let document = kuchikiki::parse_html().one(page);
348        let d = execute_lua(expand_template(document, &p, None).unwrap()).unwrap();
349        let text = d.select_first("span").unwrap().as_node().text_contents();
350        assert_eq!(text, "Test from Lua!\n");
351        assert!(d.select_first("lua").is_err());
352        let text = d.select_first("#inc1").unwrap().as_node().text_contents();
353        assert_eq!(text, "included1");
354        assert!(d.select_first("include").is_err());
355    }
356
357    #[test]
358    fn recursive_include() {
359        let page = r#"
360            <!DOCTYPE html>
361            <html>
362                <head>
363                    <title>Basic HTML Page</title>
364                </head>
365            <body>
366                <h1>Hello World</h1>
367                <include path="comp2_level1.html" />
368            </body>
369            </html>"#;
370        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
371        p.push("tests/components");
372        let document = kuchikiki::parse_html().one(page);
373        let d = expand_template(document, &p, None).unwrap();
374        let text = d.select_first("span").unwrap().as_node().text_contents();
375        assert_eq!(text, "included_twice");
376        assert!(d.select_first("include").is_err());
377    }
378
379    #[test]
380    fn export_element_include() {
381        let page = r#"
382            <!DOCTYPE html>
383            <html>
384                <head>
385                    <title>Basic HTML Page</title>
386                </head>
387            <body>
388                <h1>Hello World</h1>
389                <include path="with_include1.html">
390                    <exportelement class="el1"><span id="ta">element 1</span></exportelement>
391                    <exportelement class="el2"><span id="tb">element 2</span></exportelement>
392                </include>
393            </body>
394            </html>"#;
395        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
396        p.push("tests/components");
397        let document = kuchikiki::parse_html().one(page);
398        let d = expand_template(document, &p, None).unwrap();
399        let text = d.select_first("#ta").unwrap().as_node().text_contents();
400        assert_eq!(text, "element 1");
401        let text = d.select_first("#tb").unwrap().as_node().text_contents();
402        assert_eq!(text, "element 2");
403        assert!(d.select_first("exportelement").is_err());
404        assert!(d.select_first("includeelement").is_err());
405    }
406
407    #[test]
408    fn include_base() {
409        let page = r#"
410            <include path="include_base.html">
411                <exportelement class="t"><title>title_test</title></exportelement>
412                <exportelement class="b"><span id="tb">body_el</span></exportelement>
413            </include>
414            "#;
415        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
416        p.push("tests/components");
417        let ctx_name = QualName::new(None, ns!(html), LocalName::from("div"));
418        let document = kuchikiki::parse_fragment(ctx_name, Vec::new()).one(page);
419        let d = expand_template(document, &p, None).unwrap();
420        let text = d
421            .select_first("head")
422            .unwrap()
423            .as_node()
424            .select_first("title")
425            .unwrap()
426            .as_node()
427            .text_contents();
428        assert_eq!(text, "title_test");
429        let text = d.select_first("#tb").unwrap().as_node().text_contents();
430        assert_eq!(text, "body_el");
431        assert!(d.select_first("exportelement").is_err());
432        assert!(d.select_first("includeelement").is_err());
433    }
434
435    #[test]
436    fn footnotes() {
437        let page = r"
438            <!DOCTYPE html>
439            <html>
440            <head>
441                <title>Basic HTML Page</title>
442            </head>
443            <body>
444                <div>
445                    <p>asdf</p>
446                    <p>asdf<footnote>um actually</footnote></p>
447                    <p>asdf</p>
448                    <p>asdf<footnote>no</footnote></p>
449                </div>
450                <div>
451                <footnotecontainer></footnotecontainer>
452                </div>
453                </body>
454                </html>";
455        let document = kuchikiki::parse_html().one(page);
456        let d = generate_footnotes(document).unwrap();
457        let sup1 = d.select_first("#ft-sup-1").unwrap();
458        assert_eq!(sup1.attributes.borrow().get("title").unwrap(), "um actually");
459        assert_eq!(sup1.text_contents(), "1");
460
461        let sup2 = d.select_first("#ft-sup-2").unwrap();
462        assert_eq!(sup2.attributes.borrow().get("title").unwrap(), "no");
463        assert_eq!(sup2.text_contents(), "2");
464
465        let ft_text_1 = d.select_first("#ft-text-1").unwrap();
466        assert!(ft_text_1.text_contents().contains("um actually"));
467
468        let ft_text_2 = d.select_first("#ft-text-2").unwrap();
469        assert!(ft_text_2.text_contents().contains("no"));
470
471        assert!(d.select_first("footnote").is_err());
472        assert!(d.select_first("footnotecontainer").is_err());
473    }
474
475    #[test]
476    fn basic_markdown() {
477        let page = r"
478            <!DOCTYPE html>
479            <html>
480            <head>
481                <title>Markdown Test</title>
482            </head>
483            <body>
484                <h1>Hello World</h1>
485                <div>
486                    <markdown>
487# This is a heading
488This is a paragraph with **bold text** and *italic text*.
489
490- Item 1
491- Item 2
492- Item 3
493                    </markdown>
494                </div>
495            </body>
496            </html>";
497        let document = kuchikiki::parse_html().one(page);
498        let d = process_markdown(document).unwrap();
499        assert!(d.select_first("markdown").is_err());
500        assert!(d.select_first("p").is_ok());
501        assert!(d.select_first("ul").is_ok());
502    }
503
504    #[test]
505    fn basic_syntax_highlighting() {
506        let page = r#"
507            <!DOCTYPE html>
508            <html>
509            <head>
510                <title>Syntax Highlighting Test</title>
511            </head>
512            <body>
513                <h1>Code Example</h1>
514                <syntaxhighlight lang="rust">
515fn main() {
516    println!("Hello, world!");
517    let x = 42;
518    let y = "test";
519}
520                </syntaxhighlight>
521            </body>
522            </html>"#;
523        let document = kuchikiki::parse_html().one(page);
524        let d = process_syntax_highlighting(document).unwrap();
525        assert!(d.select_first("syntaxhighlight").is_err());
526        assert!(d.select_first("pre").is_ok());
527        assert!(d.select_first("code").is_ok());
528        let pre = d.select_first("pre").unwrap();
529        let attrs = pre.attributes.borrow();
530        assert_eq!(attrs.get("data-lang"), Some("rust"));
531        assert!(attrs.get("class").unwrap().contains("syntax-highlight"));
532    }
533
534    static SERVER_POOL: ServerPool = ServerPool::new(2);
535
536    #[test]
537    fn basic_get() {
538        let server = SERVER_POOL.get_server();
539
540        server.expect(
541            Expectation::matching(request::method_path("GET", "/test/1")).respond_with(status_code(200).body("ret")),
542        );
543
544        let stdout = Rc::new(RefCell::new(String::new()));
545        let lua = build_lua_with_stdout(&stdout).unwrap();
546        let code = format!("htmlua.print(htmlua.http.get(\"{}\").body)", server.url("/test/1"));
547        lua.load(code).exec().unwrap();
548        assert_eq!(stdout.borrow().as_str(), "ret");
549    }
550
551    #[test]
552    fn basic_post() {
553        let server = SERVER_POOL.get_server();
554
555        server.expect(
556            Expectation::matching(request::method_path("POST", "/test/1")).respond_with(status_code(200).body("ret")),
557        );
558
559        let stdout = Rc::new(RefCell::new(String::new()));
560        let lua = build_lua_with_stdout(&stdout).unwrap();
561        let code = format!("htmlua.print(htmlua.http.post(\"{}\").body)", server.url("/test/1"));
562        lua.load(code).exec().unwrap();
563        assert_eq!(stdout.borrow().as_str(), "ret");
564    }
565
566    #[test]
567    fn get_with_data() {
568        let server = SERVER_POOL.get_server();
569
570        server.expect(
571            Expectation::matching(request::query(url_decoded(contains(("a", "b")))))
572                .respond_with(status_code(200).body("ret")),
573        );
574
575        let stdout = Rc::new(RefCell::new(String::new()));
576        let lua = build_lua_with_stdout(&stdout).unwrap();
577        let code = format!(
578            "
579                data = {{}}
580                data.a = \"b\"
581                htmlua.print(htmlua.http.get_with_data(\"{}\", data).body)
582            ",
583            server.url("/test/1")
584        );
585        lua.load(code).exec().unwrap();
586        assert_eq!(stdout.borrow().as_str(), "ret");
587    }
588
589    #[test]
590    fn post_with_data_form() {
591        let server = SERVER_POOL.get_server();
592
593        server.expect(
594            Expectation::matching(all_of![request::method_path("POST", "/test/1"), request::body("a=b")])
595                .respond_with(status_code(200).body("ret")),
596        );
597
598        let stdout = Rc::new(RefCell::new(String::new()));
599        let lua = build_lua_with_stdout(&stdout).unwrap();
600        let code = format!(
601            "
602                data = {{}}
603                data.a = \"b\"
604                htmlua.print(htmlua.http.post_with_data_form(\"{}\", data).body)
605            ",
606            server.url("/test/1")
607        );
608        lua.load(code).exec().unwrap();
609        assert_eq!(stdout.borrow().as_str(), "ret");
610    }
611
612    #[test]
613    fn post_with_data_json() {
614        let server = SERVER_POOL.get_server();
615
616        server.expect(
617            Expectation::matching(all_of![request::method_path("POST", "/test/1"), request::body(r#"{"a":"b"}"#)])
618                .respond_with(status_code(200).body("ret")),
619        );
620
621        let stdout = Rc::new(RefCell::new(String::new()));
622        let lua = build_lua_with_stdout(&stdout).unwrap();
623        let code = format!(
624            "
625                data = {{}}
626                data.a = \"b\"
627                htmlua.print(htmlua.http.post_with_data_json(\"{}\", data).body)
628            ",
629            server.url("/test/1")
630        );
631        lua.load(code).exec().unwrap();
632        assert_eq!(stdout.borrow().as_str(), "ret");
633    }
634
635    #[test]
636    fn table_request() {
637        let server = SERVER_POOL.get_server();
638
639        server.expect(
640            Expectation::matching(all_of![
641                request::method_path("GET", "/test/1"),
642                request::body("cool"),
643                request::headers(contains(("testhdr", "val"))),
644                request::headers(contains(("authorization", "Basic dXNlcjpwYXNz"))),
645            ])
646            .respond_with(status_code(200).body("ret")),
647        );
648
649        let stdout = Rc::new(RefCell::new(String::new()));
650        let lua = build_lua_with_stdout(&stdout).unwrap();
651        let code = format!(
652            "
653                req = {{}}
654                req.url = \"{}\"
655                req.method = \"GET\"
656                req.headers = {{}}
657                req.headers.testhdr = \"val\"
658                req.basic_auth = {{}}
659                req.basic_auth.username = \"user\"
660                req.basic_auth.password = \"pass\"
661                req.body = \"cool\"
662
663                htmlua.print(htmlua.http.request(req).body)
664            ",
665            server.url("/test/1")
666        );
667        lua.load(code).exec().unwrap();
668        assert_eq!(stdout.borrow().as_str(), "ret");
669    }
670}