From 5e2b6bee64d58c374c8b88a270c7107f06af244e Mon Sep 17 00:00:00 2001 From: videogame hacker Date: Sun, 12 Sep 2021 22:01:01 +0100 Subject: [PATCH] Parse links from matrix messages --- src/message_ast/convert_matrix.rs | 38 ++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/src/message_ast/convert_matrix.rs b/src/message_ast/convert_matrix.rs index e1faab1..0dda458 100644 --- a/src/message_ast/convert_matrix.rs +++ b/src/message_ast/convert_matrix.rs @@ -22,7 +22,8 @@ pub fn convert_matrix(message: &str) -> MessageContent { local_name!("strong") | local_name!("b") | local_name!("em") - | local_name!("i") => { + | local_name!("i") + | local_name!("a") => { parents.push(components); components = vec![]; } @@ -57,6 +58,21 @@ pub fn convert_matrix(message: &str) -> MessageContent { local_name!("em") | local_name!("i") => { construct_component!(MessageComponent::Italic) } + local_name!("a") => { + if let Some(mut parent_components) = parents.pop() { + let attrs = element.attributes.borrow(); + if let Some(href) = attrs.get(local_name!("href")) { + parent_components.push(MessageComponent::Link { + target: href.to_string(), + text: components, + }); + } else { + parent_components.append(&mut components); + } + + components = parent_components; + } + } _ => {} } } @@ -122,14 +138,24 @@ pub fn format_matrix(message_content: &[MessageComponent]) -> String { #[test] fn simple_matrix_parsing() { - let html = r"hello! <>"; + use MessageComponent::*; + + let html = + r#"hello! <> example"#; let ast = convert_matrix(html); assert_eq!( ast, - vec![MessageComponent::Bold(vec![ - MessageComponent::Plain("hello! ".to_string(),), - MessageComponent::Italic(vec![MessageComponent::Plain("<>".to_string())]) - ])] + vec![ + Bold(vec![ + Plain("hello! ".to_string(),), + Italic(vec![Plain("<>".to_string())]), + ]), + Plain(" ".to_string()), + Link { + target: "https://example.com/".to_string(), + text: vec![Plain("example".to_string())] + }, + ] ) }