From 8e25531af188b89acd9f3283b6925f06789248af Mon Sep 17 00:00:00 2001 From: Quin Date: Sat, 5 Jul 2025 22:04:27 -0600 Subject: Added support for . Closes #4. --- htmlua-parser/src/render.rs | 65 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 57 insertions(+), 8 deletions(-) (limited to 'htmlua-parser/src/render.rs') diff --git a/htmlua-parser/src/render.rs b/htmlua-parser/src/render.rs index 58a8259..21f66ba 100644 --- a/htmlua-parser/src/render.rs +++ b/htmlua-parser/src/render.rs @@ -1,13 +1,9 @@ -use std::cell::RefCell; -use std::fmt::Write; -use std::fs::read_to_string; -use std::path::PathBuf; -use std::rc::Rc; - -use anyhow::Result; -use anyhow::anyhow; +use std::{cell::RefCell, fmt::Write, fs::read_to_string, path::PathBuf, rc::Rc}; + +use anyhow::{Result, anyhow}; use kuchikiki::{NodeRef, traits::TendrilSink}; use mlua::{Lua, Table}; +use pulldown_cmark::{Options, Parser, html}; fn create_luahtml_stdlib(l: &Lua, stdout: &Rc>) -> mlua::Result { let t = l.create_table()?; @@ -69,6 +65,30 @@ pub fn execute_lua(document: NodeRef) -> Result { Ok(document) } +pub fn process_markdown(document: NodeRef) -> Result { + 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 { if let Some(from_node) = include_from { for i in document @@ -237,4 +257,33 @@ mod tests { assert!(d.select_first("exportelement").is_err()); assert!(d.select_first("includeelement").is_err()); } + + #[test] + fn basic_markdown() { + let page = r#" + + + + Markdown Test + + +

Hello World

+
+ +# This is a heading +This is a paragraph with **bold text** and *italic text*. + +- Item 1 +- Item 2 +- Item 3 + +
+ + "#; + 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()); + } } -- cgit v1.3.1