summaryrefslogtreecommitdiff
path: root/htmlua-parser/src/render.rs
blob: 7046db8b9f003a7ead8f3b80759d2c24e8956279 (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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
use std::{
    cell::{LazyCell, RefCell},
    fmt::Write,
    path::PathBuf,
    rc::Rc,
};

use anyhow::{Result, anyhow};
use kuchikiki::{NodeRef, traits::TendrilSink};
use markup5ever::{LocalName, Namespace, QualName};
use mlua::{Lua, Table};
use pulldown_cmark::{Options, Parser, html};
use syntect::{
    easy::HighlightLines,
    highlighting::{Style, ThemeSet},
    html::{IncludeBackground, styled_line_to_highlighted_html},
    parsing::SyntaxSet,
    util::LinesWithEndings,
};

use crate::{helpers::read_doc_from_file, htmlua_stdlib::create_htmlua_stdlib, serve::get_config};


fn build_lua_with_stdout(stdout: &Rc<RefCell<String>>) -> Result<Lua> {
    let lua = Lua::new();
    let globals = lua.globals();

    let htmlua_table = create_htmlua_stdlib(&lua, stdout).map_err(|e| anyhow!("Failed to create Lua stdlib: {}", e))?;

    globals
        .set("htmlua", htmlua_table)
        .map_err(|e| anyhow!("Failed to set global: {}", e))?;

    Ok(lua)
}

pub fn execute_lua(document: NodeRef) -> Result<NodeRef> {
    let stdout: Rc<RefCell<String>> = Rc::new(RefCell::new(String::new()));
    let lua = LazyCell::new(|| build_lua_with_stdout(&stdout).unwrap_or_default());
    let lua_elements: Vec<_> = match document.select("lua") {
        Ok(e) => e.collect(),
        Err(()) => return Err(anyhow!("Unable to find Lua")),
    };

    for node in lua_elements {
        if let Some(text_node) = node.as_node().first_child() {
            if let Some(lua_code) = text_node.as_text() {
                stdout.borrow_mut().clear();
                lua.load(lua_code.borrow().as_str())
                    .exec()
                    .map_err(|e| anyhow!("Failed to execute Lua: {}", e))?;
                node.as_node()
                    .insert_before(NodeRef::new_text(stdout.borrow().as_str()));
                node.as_node().detach();
            }
        }
    }

    Ok(document)
}

pub fn process_markdown(document: NodeRef) -> Result<NodeRef> {
    let markdown_elements: Vec<_> = match document.select("markdown") {
        Ok(e) => e.collect(),
        Err(()) => return Err(anyhow!("Unable to find markdown elements")),
    };
    for node in markdown_elements {
        if let Some(text_node) = node.as_node().first_child() {
            if let Some(markdown_text) = text_node.as_text() {
                let borrowed_text = markdown_text.borrow();
                let parser = Parser::new_ext(&borrowed_text, Options::all());
                let mut html_output = String::new();
                html::push_html(&mut html_output, parser);
                let html_fragment = kuchikiki::parse_html().one(html_output);
                for child in html_fragment.children() {
                    node.as_node().insert_before(child);
                }
                // Remove the original markdown node.
                node.as_node().detach();
            }
        }
    }
    Ok(document)
}

pub fn expand_template(document: NodeRef, component_path: &PathBuf, include_from: Option<&NodeRef>) -> Result<NodeRef> {
    if let Some(from_node) = include_from {
        for i in document
            .select("includeelement")
            .map_err(|()| anyhow!("Error finding includeelement"))?
        {
            if let Some(name) = i.attributes.borrow().get("name") {
                let exported = from_node
                    .select_first(format!("exportelement.{name}").as_str())
                    .map_err(|()| anyhow!("Error finding exportelement"))?;
                exported
                    .as_node()
                    .children()
                    .rev()
                    .for_each(|c| i.as_node().insert_after(c));
            }
        }
        while let Ok(i) = document.select_first("includeelement") {
            i.as_node().detach();
        }
    }

    for i in document
        .select("include")
        .map_err(|()| anyhow!("Error finding include"))?
        .collect::<Vec<_>>()
    {
        let attrs = match i.as_node().as_element() {
            Some(e) => e.attributes.borrow(),
            None => continue,
        };
        if let Some(include_path) = attrs.get("path") {
            let mut item_path = component_path.clone();
            item_path.push(include_path);
            let new_node = read_doc_from_file(item_path)?;
            let replaced_node = expand_template(new_node, component_path, Some(i.as_node()))?;
            replaced_node
                .select_first("html")
                .map_err(|()| anyhow!("Error finding html"))?
                .as_node()
                .children()
                .rev()
                .for_each(|c| i.as_node().insert_after(c));
        }
    }
    while let Ok(i) = document.select_first("include") {
        i.as_node().detach();
    }
    Ok(document)
}

pub fn process_syntax_highlighting(document: NodeRef) -> Result<NodeRef> {
    let config = get_config();
    let ps = SyntaxSet::load_defaults_newlines();
    let mut ts = ThemeSet::load_defaults();
    let syntax_elements: Vec<_> = match document.select("syntaxhighlight") {
        Ok(e) => e.collect(),
        Err(()) => return Err(anyhow!("Unable to find syntaxhighlight elements")),
    };
    if !syntax_elements.is_empty() && config.syntax_highlighting.load_custom_themes {
        let _ = ts.add_from_folder(&config.paths.themes);
    }
    for node in syntax_elements {
        let attrs = match node.as_node().as_element() {
            Some(e) => e.attributes.borrow(),
            None => continue,
        };
        let language = attrs.get("lang").unwrap_or("text");
        let theme_name = attrs.get("theme").unwrap_or(&config.syntax_highlighting.default_theme);
        if let Some(text_node) = node.as_node().first_child() {
            if let Some(code_text) = text_node.as_text() {
                let syntax = ps
                    .find_syntax_by_extension(language)
                    .or_else(|| ps.find_syntax_by_name(language))
                    .unwrap_or_else(|| ps.find_syntax_plain_text());
                let theme = &ts.themes[theme_name];
                let mut h = HighlightLines::new(syntax, theme);
                let mut html_output = String::new();
                write!(html_output, r#"<pre class="syntax-highlight" data-lang="{language}">"#)?;
                html_output.push_str("<code>");
                for line in LinesWithEndings::from(&code_text.borrow()) {
                    let ranges: Vec<(Style, &str)> = h.highlight_line(line, &ps)?;
                    let escaped = styled_line_to_highlighted_html(&ranges[..], IncludeBackground::No)?;
                    html_output.push_str(&escaped);
                }
                html_output.push_str("</code></pre>");
                let html_fragment = kuchikiki::parse_html().one(html_output);
                for child in html_fragment.children() {
                    node.as_node().insert_before(child);
                }
                // Remove the original syntaxhighlight node.
                node.as_node().detach();
            }
        }
    }
    Ok(document)
}

pub fn generate_footnotes(document: NodeRef) -> Result<NodeRef> {
    let Ok(footnote_container) = document.select_first("footnotecontainer") else {
        return Ok(document);
    };

    let ctx_name = QualName::new(None, Namespace::from("http://www.w3.org/1999/xhtml"), LocalName::from("div"));
    for (i, footnote) in document
        .select("footnote")
        .map_err(|()| anyhow!("Failed to get footnote"))?
        .enumerate()
    {
        let i = i + 1;
        let fn_text = footnote.text_contents();
        let sup_tag = kuchikiki::parse_fragment(ctx_name.clone(), Vec::new())
            .one(format!("<a href=#ft-text-{i}><sup id=\"ft-sup-{i}\" title=\"{fn_text}\">{i}</sup></a>"))
            .select_first("a")
            .map_err(|()| anyhow!("parse err"))?;
        footnote.as_node().insert_after(sup_tag.as_node().clone());
        let text_tag = kuchikiki::parse_fragment(ctx_name.clone(), Vec::new())
            .one(format!("<p id=\"ft-text-{i}\"><a href=#ft-sup-{i}>{i}:</a> {fn_text}</p>"))
            .select_first("p")
            .map_err(|()| anyhow!("parse err"))?;
        footnote_container.as_node().insert_before(text_tag.as_node().clone());
    }
    while let Ok(i) = document.select_first("footnote") {
        i.as_node().detach();
    }
    footnote_container.as_node().detach();
    Ok(document)
}

#[cfg(test)]
mod tests {
    use httptest::{Expectation, ServerPool, matchers::*, responders::*};

    use super::*;

    #[test]
    fn basic_lua() {
        let page = r#"
            <!DOCTYPE html>
            <html>
            <head>
                <title>Basic HTML Page</title>
            </head>
            <body>
                <h1>Hello World</h1>
                <p>This is a paragraph.</p>
                <span><lua>
                    htmlua.println("Test from Lua!")
                </lua></span>
            </body>
            </html>"#;
        let document = kuchikiki::parse_html().one(page);
        let d = execute_lua(document).unwrap();
        let text = d.select_first("span").unwrap().as_node().text_contents();
        assert_eq!(text, "Test from Lua!\n");
        assert!(d.select_first("lua").is_err());
    }

    #[test]
    fn multiple_lua() {
        let page = r#"
            <!DOCTYPE html>
            <html>
            <head>
                <title>Basic HTML Page</title>
            </head>
            <body>
                <h1>Hello World</h1>
                <p>This is a paragraph.</p>
                <span id="ta"><lua>
                    htmlua.println("Test from Lua!")
                </lua></span>
                <div>
                    <span id="tb"><lua>htmlua.println("test 2")</lua></span>
                </div>
            </body>
            </html>"#;
        let document = kuchikiki::parse_html().one(page);
        let d = execute_lua(document).unwrap();
        let text = d.select_first("#ta").unwrap().as_node().text_contents();
        assert_eq!(text, "Test from Lua!\n");
        let text = d.select_first("#tb").unwrap().as_node().text_contents();
        assert_eq!(text, "test 2\n");
        assert!(d.select_first("lua").is_err());
    }

    #[test]
    fn basic_include() {
        let page = r#"
            <!DOCTYPE html>
            <html>
            <head>
                <title>Basic HTML Page</title>
            </head>
            <body>
                <h1>Hello World</h1>
                <p>This is a paragraph.</p>
                <include path="comp1.html" />
                <span><lua>
                    htmlua.println("Test from Lua!")
                </lua></span>
            </body>
            </html>"#;
        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        p.push("tests/components");
        let document = kuchikiki::parse_html().one(page);
        let d = expand_template(document, &p, None).unwrap();
        let text = d.select_first("span").unwrap().as_node().text_contents();
        assert_eq!(text, "included1");
        assert!(d.select_first("include").is_err());
    }

    #[test]
    fn multiple_include() {
        let page = r#"
            <!DOCTYPE html>
            <html>
            <head>
                <title>Basic HTML Page</title>
            </head>
            <body>
                <h1>Hello World</h1>
                <p>This is a paragraph.</p>
                <include path="multi1_1.html"></include>
                <include path="multi1_2.html"></include>
                <include path="multi1_3.html"></include>
            </body>
            </html>"#;
        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        p.push("tests/components");
        let document = kuchikiki::parse_html().one(page);
        let d = expand_template(document, &p, None).unwrap();
        let text = d.select_first("#inc1").unwrap().as_node().text_contents();
        assert_eq!(text, "included1");
        let text = d.select_first("#inc2").unwrap().as_node().text_contents();
        assert_eq!(text, "included2");
        let text = d.select_first("#inc3").unwrap().as_node().text_contents();
        assert_eq!(text, "included3");
        assert!(d.select_first("include").is_err());
    }

    #[test]
    fn basic_lua_include() {
        let page = r#"
            <!DOCTYPE html>
            <html>
            <head>
                <title>Basic HTML Page</title>
            </head>
            <body>
                <h1>Hello World</h1>
                <p>This is a paragraph.</p>
                <span><lua>
                    htmlua.println("Test from Lua!")
                </lua></span>
                <include path="comp1.html" />
            </body>
            </html>"#;
        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        p.push("tests/components");
        let document = kuchikiki::parse_html().one(page);
        let d = execute_lua(expand_template(document, &p, None).unwrap()).unwrap();
        let text = d.select_first("span").unwrap().as_node().text_contents();
        println!("{}", d.to_string());
        assert_eq!(text, "Test from Lua!\n");
        assert!(d.select_first("lua").is_err());
        let text = d.select_first("#inc1").unwrap().as_node().text_contents();
        assert_eq!(text, "included1");
        assert!(d.select_first("include").is_err());
    }

    #[test]
    fn recursive_include() {
        let page = r#"
            <!DOCTYPE html>
            <html>
                <head>
                    <title>Basic HTML Page</title>
                </head>
            <body>
                <h1>Hello World</h1>
                <include path="comp2_level1.html" />
            </body>
            </html>"#;
        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        p.push("tests/components");
        let document = kuchikiki::parse_html().one(page);
        let d = expand_template(document, &p, None).unwrap();
        let text = d.select_first("span").unwrap().as_node().text_contents();
        assert_eq!(text, "included_twice");
        assert!(d.select_first("include").is_err());
    }

    #[test]
    fn export_element_include() {
        let page = r#"
            <!DOCTYPE html>
            <html>
                <head>
                    <title>Basic HTML Page</title>
                </head>
            <body>
                <h1>Hello World</h1>
                <include path="with_include1.html">
                    <exportelement class="el1"><span id="ta">element 1</span></exportelement>
                    <exportelement class="el2"><span id="tb">element 2</span></exportelement>
                </include>
            </body>
            </html>"#;
        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        p.push("tests/components");
        let document = kuchikiki::parse_html().one(page);
        let d = expand_template(document, &p, None).unwrap();
        let text = d.select_first("#ta").unwrap().as_node().text_contents();
        assert_eq!(text, "element 1");
        let text = d.select_first("#tb").unwrap().as_node().text_contents();
        assert_eq!(text, "element 2");
        assert!(d.select_first("exportelement").is_err());
        assert!(d.select_first("includeelement").is_err());
    }

    #[test]
    fn footnotes() {
        let page = r"
            <!DOCTYPE html>
            <html>
            <head>
                <title>Basic HTML Page</title>
            </head>
            <body>
                <div>
                    <p>asdf</p>
                    <p>asdf<footnote>um actually</footnote></p>
                    <p>asdf</p>
                    <p>asdf<footnote>no</footnote></p>
                </div>
                <div>
                <footnotecontainer></footnotecontainer>
                </div>
                </body>
                </html>";
        let document = kuchikiki::parse_html().one(page);
        let d = generate_footnotes(document).unwrap();
        let sup1 = d.select_first("#ft-sup-1").unwrap();
        assert_eq!(sup1.attributes.borrow().get("title").unwrap(), "um actually");
        assert_eq!(sup1.text_contents(), "1");

        let sup2 = d.select_first("#ft-sup-2").unwrap();
        assert_eq!(sup2.attributes.borrow().get("title").unwrap(), "no");
        assert_eq!(sup2.text_contents(), "2");

        let ft_text_1 = d.select_first("#ft-text-1").unwrap();
        assert!(ft_text_1.text_contents().contains("um actually"));

        let ft_text_2 = d.select_first("#ft-text-2").unwrap();
        assert!(ft_text_2.text_contents().contains("no"));

        assert!(d.select_first("footnote").is_err());
        assert!(d.select_first("footnotecontainer").is_err());
    }

    #[test]
    fn basic_markdown() {
        let page = r"
            <!DOCTYPE html>
            <html>
            <head>
                <title>Markdown Test</title>
            </head>
            <body>
                <h1>Hello World</h1>
                <div>
                    <markdown>
# This is a heading
This is a paragraph with **bold text** and *italic text*.

- Item 1
- Item 2
- Item 3
                    </markdown>
                </div>
            </body>
            </html>";
        let document = kuchikiki::parse_html().one(page);
        let d = process_markdown(document).unwrap();
        assert!(d.select_first("markdown").is_err());
        assert!(d.select_first("p").is_ok());
        assert!(d.select_first("ul").is_ok());
    }

    #[test]
    fn basic_syntax_highlighting() {
        let page = r#"
            <!DOCTYPE html>
            <html>
            <head>
                <title>Syntax Highlighting Test</title>
            </head>
            <body>
                <h1>Code Example</h1>
                <syntaxhighlight lang="rust">
fn main() {
    println!("Hello, world!");
    let x = 42;
    let y = "test";
}
                </syntaxhighlight>
            </body>
            </html>"#;
        let document = kuchikiki::parse_html().one(page);
        let d = process_syntax_highlighting(document).unwrap();
        assert!(d.select_first("syntaxhighlight").is_err());
        assert!(d.select_first("pre").is_ok());
        assert!(d.select_first("code").is_ok());
        let pre = d.select_first("pre").unwrap();
        let attrs = pre.attributes.borrow();
        assert_eq!(attrs.get("data-lang"), Some("rust"));
        assert!(attrs.get("class").unwrap().contains("syntax-highlight"));
    }

    static SERVER_POOL: ServerPool = ServerPool::new(2);

    #[test]
    fn basic_get() {
        let server = SERVER_POOL.get_server();

        server.expect(
            Expectation::matching(request::method_path("GET", "/test/1")).respond_with(status_code(200).body("ret")),
        );

        let stdout = Rc::new(RefCell::new(String::new()));
        let lua = build_lua_with_stdout(&stdout).unwrap();
        let code = format!("htmlua.print(htmlua.http.get(\"{}\").body)", server.url("/test/1"));
        lua.load(code).exec().unwrap();
        assert_eq!(stdout.borrow().as_str(), "ret");
    }

    #[test]
    fn basic_post() {
        let server = SERVER_POOL.get_server();

        server.expect(
            Expectation::matching(request::method_path("POST", "/test/1")).respond_with(status_code(200).body("ret")),
        );

        let stdout = Rc::new(RefCell::new(String::new()));
        let lua = build_lua_with_stdout(&stdout).unwrap();
        let code = format!("htmlua.print(htmlua.http.post(\"{}\").body)", server.url("/test/1"));
        lua.load(code).exec().unwrap();
        assert_eq!(stdout.borrow().as_str(), "ret");
    }

    #[test]
    fn get_with_data() {
        let server = SERVER_POOL.get_server();

        server.expect(
            Expectation::matching(request::query(url_decoded(contains(("a", "b")))))
                .respond_with(status_code(200).body("ret")),
        );

        let stdout = Rc::new(RefCell::new(String::new()));
        let lua = build_lua_with_stdout(&stdout).unwrap();
        let code = format!(
            "
                data = {{}}
                data.a = \"b\"
                htmlua.print(htmlua.http.get_with_data(\"{}\", data).body)
            ",
            server.url("/test/1")
        );
        lua.load(code).exec().unwrap();
        assert_eq!(stdout.borrow().as_str(), "ret");
    }

    #[test]
    fn post_with_data_form() {
        let server = SERVER_POOL.get_server();

        server.expect(
            Expectation::matching(all_of![request::method_path("POST", "/test/1"), request::body("a=b")])
                .respond_with(status_code(200).body("ret")),
        );

        let stdout = Rc::new(RefCell::new(String::new()));
        let lua = build_lua_with_stdout(&stdout).unwrap();
        let code = format!(
            "
                data = {{}}
                data.a = \"b\"
                htmlua.print(htmlua.http.post_with_data_form(\"{}\", data).body)
            ",
            server.url("/test/1")
        );
        lua.load(code).exec().unwrap();
        assert_eq!(stdout.borrow().as_str(), "ret");
    }

    #[test]
    fn post_with_data_json() {
        let server = SERVER_POOL.get_server();

        server.expect(
            Expectation::matching(all_of![request::method_path("POST", "/test/1"), request::body(r#"{"a":"b"}"#)])
                .respond_with(status_code(200).body("ret")),
        );

        let stdout = Rc::new(RefCell::new(String::new()));
        let lua = build_lua_with_stdout(&stdout).unwrap();
        let code = format!(
            "
                data = {{}}
                data.a = \"b\"
                htmlua.print(htmlua.http.post_with_data_json(\"{}\", data).body)
            ",
            server.url("/test/1")
        );
        lua.load(code).exec().unwrap();
        assert_eq!(stdout.borrow().as_str(), "ret");
    }

    #[test]
    fn table_request() {
        let server = SERVER_POOL.get_server();

        server.expect(
            Expectation::matching(all_of![
                request::method_path("GET", "/test/1"),
                request::body("cool"),
                request::headers(contains(("testhdr", "val"))),
                request::headers(contains(("authorization", "Basic dXNlcjpwYXNz"))),
            ])
            .respond_with(status_code(200).body("ret")),
        );

        let stdout = Rc::new(RefCell::new(String::new()));
        let lua = build_lua_with_stdout(&stdout).unwrap();
        let code = format!(
            "
                req = {{}}
                req.url = \"{}\"
                req.method = \"GET\"
                req.headers = {{}}
                req.headers.testhdr = \"val\"
                req.basic_auth = {{}}
                req.basic_auth.username = \"user\"
                req.basic_auth.password = \"pass\"
                req.body = \"cool\"

                htmlua.print(htmlua.http.request(req).body)
            ",
            server.url("/test/1")
        );
        lua.load(code).exec().unwrap();
        assert_eq!(stdout.borrow().as_str(), "ret");
    }
}