From 3c366f74bbc0a9be8b3796834d8a2b0dd5635a4f Mon Sep 17 00:00:00 2001 From: Timeless0911 <50201324+Timeless0911@users.noreply.github.com> Date: Thu, 16 May 2024 14:24:02 +0800 Subject: [PATCH] fix: trim_end when collect title in mdast (#42) --- crates/plugin_toc/src/lib.rs | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/plugin_toc/src/lib.rs b/crates/plugin_toc/src/lib.rs index de0e273..3ae903a 100644 --- a/crates/plugin_toc/src/lib.rs +++ b/crates/plugin_toc/src/lib.rs @@ -25,7 +25,7 @@ pub struct TocResult { pub enum NodeType { Link, Strong, - Emphasis + Emphasis, } pub fn extract_text_from_node(node: &mdast::Node, node_type: NodeType) -> String { @@ -48,7 +48,10 @@ pub fn extract_text_from_node(node: &mdast::Node, node_type: NodeType) -> String if let mdast::Node::Emphasis(emphasis) = node { // Emphasis&Strong: ***hello*** if let mdast::Node::Strong(_) = &emphasis.children[0] { - return format!("**{}**", extract_text_from_node(&emphasis.children[0], NodeType::Strong)); + return format!( + "**{}**", + extract_text_from_node(&emphasis.children[0], NodeType::Strong) + ); } if let mdast::Node::Text(text) = &emphasis.children[0] { return text.value.clone(); @@ -83,6 +86,7 @@ pub fn collect_title_in_mdast(heading: &mut Heading) -> (String, String) { _ => continue, // Continue if node is not Text or Code } } + title = title.trim_end().to_string(); (title, custom_id) } @@ -174,6 +178,29 @@ mod tests { })], position: None, }; + let mut heading4 = mdast::Heading { + depth: 1, + children: vec![ + mdast::Node::Text(mdast::Text { + value: "Hello World ".to_string(), + position: None, + }), + mdast::Node::MdxJsxFlowElement(mdast::MdxJsxFlowElement { + name: Some("foo".to_string()), + attributes: vec![], + children: vec![mdast::Node::Text(mdast::Text { + value: "bar".to_string(), + position: None, + })], + position: None, + }), + mdast::Node::Text(mdast::Text { + value: " ".to_string(), + position: None, + }), + ], + position: None, + }; assert_eq!( collect_title_in_mdast(&mut heading), @@ -187,6 +214,10 @@ mod tests { collect_title_in_mdast(&mut heading3), ("***Hello World***".to_string(), "".to_string()) ); + assert_eq!( + collect_title_in_mdast(&mut heading4), + ("Hello World".to_string(), "".to_string()) + ); } #[test]