grace/htmlua
HTML Templating Engine
git clone https://git.gae.moe/grace/htmlua
4144fa2
httpstdlib
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 :: { 8easy :: HighlightLines , 9highlighting :: { Style , ThemeSet } , 10html :: { IncludeBackground , styled_line_to_highlighted_html } , 11parsing :: SyntaxSet , 12util :: 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 > { 20let lua = Lua :: new () ; 21let globals = lua . globals () ; 22 23let stdout : Rc < RefCell < String >> = Rc :: new ( RefCell :: new ( String :: new ())) ; 24 25let htmlua_table = 26create_htmlua_stdlib ( & lua , & stdout ) . map_err ( | e | anyhow ! ( "Failed to create Lua stdlib: {}" , e )) ? ; 27 28globals 29. set ( "htmlua" , htmlua_table ) 30. map_err ( | e | anyhow ! ( "Failed to set global: {}" , e )) ? ; 31 32let lua_elements : Vec < _ > = match document . select ( "lua" ) { 33Ok ( e ) => e . collect () , 34Err (()) => return Err ( anyhow ! ( "Unable to find Lua" )) , 35} ; 36 37for node in lua_elements { 38if let Some ( text_node ) = node . as_node () . first_child () { 39if let Some ( lua_code ) = text_node . as_text () { 40stdout . borrow_mut () . clear () ; 41lua . load ( lua_code . borrow () . as_str ()) 42. exec () 43. map_err ( | e | anyhow ! ( "Failed to execute Lua: {}" , e )) ? ; 44node . as_node () 45. insert_before ( NodeRef :: new_text ( stdout . borrow () . as_str ())) ; 46node . as_node () . detach () ; 47} 48} 49} 50 51Ok ( document ) 52} 53 54pub fn process_markdown ( document : NodeRef ) -> Result < NodeRef > { 55let markdown_elements : Vec < _ > = match document . select ( "markdown" ) { 56Ok ( e ) => e . collect () , 57Err (()) => return Err ( anyhow ! ( "Unable to find markdown elements" )) , 58} ; 59for node in markdown_elements { 60if let Some ( text_node ) = node . as_node () . first_child () { 61if let Some ( markdown_text ) = text_node . as_text () { 62let borrowed_text = markdown_text . borrow () ; 63let parser = Parser :: new_ext ( & borrowed_text , Options :: all ()) ; 64let mut html_output = String :: new () ; 65html :: push_html ( & mut html_output , parser ) ; 66let html_fragment = kuchikiki :: parse_html () . one ( html_output ) ; 67for child in html_fragment . children () { 68node . as_node () . insert_before ( child ) ; 69} 70// Remove the original markdown node. 71node . as_node () . detach () ; 72} 73} 74} 75Ok ( document ) 76} 77 78pub fn expand_template ( document : NodeRef , component_path : & PathBuf , include_from : Option <& NodeRef > ) -> Result < NodeRef > { 79if let Some ( from_node ) = include_from { 80for i in document 81. select ( "includeelement" ) 82. map_err ( | () | anyhow ! ( "Error finding includeelement" )) ? 83{ 84if let Some ( name ) = i . attributes . borrow () . get ( "name" ) { 85let exported = from_node 86. select_first ( format ! ( "exportelement.{name}" ) . as_str ()) 87. map_err ( | () | anyhow ! ( "Error finding exportelement" )) ? ; 88exported . as_node () . children () . rev () . for_each ( | c | i . as_node () . insert_after ( c )) ; 89} 90} 91while let Ok ( i ) = document . select_first ( "includeelement" ) { 92i . as_node () . detach () ; 93} 94} 95 96for i in document 97. select ( "include" ) 98. map_err ( | () | anyhow ! ( "Error finding include" )) ? 99. collect :: < Vec < _ >> () 100{ 101let attrs = match i . as_node () . as_element () { 102Some ( e ) => e . attributes . borrow () , 103None => continue , 104} ; 105if let Some ( include_path ) = attrs . get ( "path" ) { 106let mut item_path = component_path . clone () ; 107item_path . push ( include_path ) ; 108let new_node = read_doc_from_file ( item_path ) ? ; 109let replaced_node = expand_template ( new_node , component_path , Some ( i . as_node ())) ? ; 110replaced_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} 114while let Ok ( i ) = document . select_first ( "include" ) { 115i . as_node () . detach () ; 116} 117Ok ( document ) 118} 119 120pub fn process_syntax_highlighting ( document : NodeRef ) -> Result < NodeRef > { 121let ps = SyntaxSet :: load_defaults_newlines () ; 122let mut ts = ThemeSet :: load_defaults () ; 123let syntax_elements : Vec < _ > = match document . select ( "syntaxhighlight" ) { 124Ok ( e ) => e . collect () , 125Err (()) => return Err ( anyhow ! ( "Unable to find syntaxhighlight elements" )) , 126} ; 127if ! syntax_elements . is_empty () { 128// TODO: read from config 129let themes = PathBuf :: from ( "/var/www/htmlua/themes" ) ; 130let _ = ts . add_from_folder ( themes ) ; 131} 132for node in syntax_elements { 133let attrs = match node . as_node () . as_element () { 134Some ( e ) => e . attributes . borrow () , 135None => continue , 136} ; 137let language = attrs . get ( "lang" ) . unwrap_or ( "text" ) ; 138let theme_name = attrs . get ( "theme" ) . unwrap_or ( "base16-ocean.dark" ) ; 139if let Some ( text_node ) = node . as_node () . first_child () { 140if let Some ( code_text ) = text_node . as_text () { 141let 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 ()) ; 145let theme = & ts . themes [ theme_name ] ; 146let mut h = HighlightLines :: new ( syntax , theme ) ; 147let mut html_output = String :: new () ; 148write ! ( html_output , r#"<pre class="syntax-highlight" data-lang="{language}">"# ) ? ; 149html_output . push_str ( "<code>" ) ; 150for line in LinesWithEndings :: from ( & code_text . borrow ()) { 151let ranges : Vec < ( Style , & str ) > = h . highlight_line ( line , & ps ) ? ; 152let escaped = styled_line_to_highlighted_html ( & ranges [ .. ] , IncludeBackground :: No ) ? ; 153html_output . push_str ( & escaped ) ; 154} 155html_output . push_str ( "</code></pre>" ) ; 156let html_fragment = kuchikiki :: parse_html () . one ( html_output ) ; 157for child in html_fragment . children () { 158node . as_node () . insert_before ( child ) ; 159} 160// Remove the original syntaxhighlight node. 161node . as_node () . detach () ; 162} 163} 164} 165Ok ( document ) 166} 167 168#[ cfg ( test ) ] 169mod tests { 170use super :: * ; 171 172#[ test ] 173fn basic_lua () { 174let 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> 184htmlua.println("Test from Lua!") 185</lua></span> 186</body> 187</html>"# ; 188let document = kuchikiki :: parse_html () . one ( page ) ; 189let d = execute_lua ( document ) . unwrap () ; 190let text = d . select_first ( "span" ) . unwrap () . as_node () . text_contents () ; 191assert_eq ! ( text , "Test from Lua! \n " ) ; 192assert ! ( d . select_first ( "lua" ) . is_err ()) ; 193} 194 195#[ test ] 196fn multiple_lua () { 197let 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> 207htmlua.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>"# ; 214let document = kuchikiki :: parse_html () . one ( page ) ; 215let d = execute_lua ( document ) . unwrap () ; 216let text = d . select_first ( "#ta" ) . unwrap () . as_node () . text_contents () ; 217assert_eq ! ( text , "Test from Lua! \n " ) ; 218let text = d . select_first ( "#tb" ) . unwrap () . as_node () . text_contents () ; 219assert_eq ! ( text , "test 2 \n " ) ; 220assert ! ( d . select_first ( "lua" ) . is_err ()) ; 221} 222 223#[ test ] 224fn basic_include () { 225let 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> 236htmlua.println("Test from Lua!") 237</lua></span> 238</body> 239</html>"# ; 240let mut p = PathBuf :: from ( env ! ( "CARGO_MANIFEST_DIR" )) ; 241p . push ( "tests/components" ) ; 242let document = kuchikiki :: parse_html () . one ( page ) ; 243let d = expand_template ( document , & p , None ) . unwrap () ; 244let text = d . select_first ( "span" ) . unwrap () . as_node () . text_contents () ; 245assert_eq ! ( text , "included1" ) ; 246assert ! ( d . select_first ( "include" ) . is_err ()) ; 247} 248 249#[ test ] 250fn multiple_include () { 251let 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>"# ; 265let mut p = PathBuf :: from ( env ! ( "CARGO_MANIFEST_DIR" )) ; 266p . push ( "tests/components" ) ; 267let document = kuchikiki :: parse_html () . one ( page ) ; 268let d = expand_template ( document , & p , None ) . unwrap () ; 269let text = d . select_first ( "#inc1" ) . unwrap () . as_node () . text_contents () ; 270assert_eq ! ( text , "included1" ) ; 271let text = d . select_first ( "#inc2" ) . unwrap () . as_node () . text_contents () ; 272assert_eq ! ( text , "included2" ) ; 273let text = d . select_first ( "#inc3" ) . unwrap () . as_node () . text_contents () ; 274assert_eq ! ( text , "included3" ) ; 275assert ! ( d . select_first ( "include" ) . is_err ()) ; 276} 277 278#[ test ] 279fn basic_lua_include () { 280let 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> 290htmlua.println("Test from Lua!") 291</lua></span> 292<include path="comp1.html" /> 293</body> 294</html>"# ; 295let mut p = PathBuf :: from ( env ! ( "CARGO_MANIFEST_DIR" )) ; 296p . push ( "tests/components" ) ; 297let document = kuchikiki :: parse_html () . one ( page ) ; 298let d = execute_lua ( expand_template ( document , & p , None ) . unwrap ()) . unwrap () ; 299let text = d . select_first ( "span" ) . unwrap () . as_node () . text_contents () ; 300println ! ( "{}" , d . to_string ()) ; 301assert_eq ! ( text , "Test from Lua! \n " ) ; 302assert ! ( d . select_first ( "lua" ) . is_err ()) ; 303let text = d . select_first ( "#inc1" ) . unwrap () . as_node () . text_contents () ; 304assert_eq ! ( text , "included1" ) ; 305assert ! ( d . select_first ( "include" ) . is_err ()) ; 306} 307 308#[ test ] 309fn recursive_include () { 310let 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>"# ; 321let mut p = PathBuf :: from ( env ! ( "CARGO_MANIFEST_DIR" )) ; 322p . push ( "tests/components" ) ; 323let document = kuchikiki :: parse_html () . one ( page ) ; 324let d = expand_template ( document , & p , None ) . unwrap () ; 325let text = d . select_first ( "span" ) . unwrap () . as_node () . text_contents () ; 326assert_eq ! ( text , "included_twice" ) ; 327assert ! ( d . select_first ( "include" ) . is_err ()) ; 328} 329 330#[ test ] 331fn export_element_include () { 332let 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>"# ; 346let mut p = PathBuf :: from ( env ! ( "CARGO_MANIFEST_DIR" )) ; 347p . push ( "tests/components" ) ; 348let document = kuchikiki :: parse_html () . one ( page ) ; 349let d = expand_template ( document , & p , None ) . unwrap () ; 350let text = d . select_first ( "#ta" ) . unwrap () . as_node () . text_contents () ; 351assert_eq ! ( text , "element 1" ) ; 352let text = d . select_first ( "#tb" ) . unwrap () . as_node () . text_contents () ; 353assert_eq ! ( text , "element 2" ) ; 354assert ! ( d . select_first ( "exportelement" ) . is_err ()) ; 355assert ! ( d . select_first ( "includeelement" ) . is_err ()) ; 356} 357 358#[ test ] 359fn basic_markdown () { 360let 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>" ; 380let document = kuchikiki :: parse_html () . one ( page ) ; 381let d = process_markdown ( document ) . unwrap () ; 382assert ! ( d . select_first ( "markdown" ) . is_err ()) ; 383assert ! ( d . select_first ( "p" ) . is_ok ()) ; 384assert ! ( d . select_first ( "ul" ) . is_ok ()) ; 385} 386 387#[ test ] 388fn basic_syntax_highlighting () { 389let 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() { 399println!("Hello, world!"); 400let x = 42; 401let y = "test"; 402} 403</syntaxhighlight> 404</body> 405</html>"# ; 406let document = kuchikiki :: parse_html () . one ( page ) ; 407let d = process_syntax_highlighting ( document ) . unwrap () ; 408assert ! ( d . select_first ( "syntaxhighlight" ) . is_err ()) ; 409assert ! ( d . select_first ( "pre" ) . is_ok ()) ; 410assert ! ( d . select_first ( "code" ) . is_ok ()) ; 411let pre = d . select_first ( "pre" ) . unwrap () ; 412let attrs = pre . attributes . borrow () ; 413assert_eq ! ( attrs . get ( "data-lang" ) , Some ( "rust" )) ; 414assert ! ( attrs . get ( "class" ) . unwrap () . contains ( "syntax-highlight" )) ; 415} 416}