Allow object links with custom text

This commit is contained in:
silverpill 2022-10-26 00:36:07 +00:00
parent acad0f260b
commit 23dca1b4c5

View file

@ -7,7 +7,7 @@ use crate::errors::DatabaseError;
use super::helpers::get_post_by_object_id;
use super::types::Post;
const OBJECT_LINK_SEARCH_RE: &str = r"(?m)\[\[(?P<url>\S+)\]\]";
const OBJECT_LINK_SEARCH_RE: &str = r"(?m)\[\[(?P<url>[^\s\|]+)(\|(?P<text>.+?))?\]\]";
fn is_inside_code_block(caps: &Captures, text: &str) -> bool {
// TODO: remove workaround.
@ -60,8 +60,12 @@ pub fn replace_object_links(
let mention_re = Regex::new(OBJECT_LINK_SEARCH_RE).unwrap();
let result = mention_re.replace_all(text, |caps: &Captures| {
let url = caps["url"].to_string();
let link_text = caps.name("text")
.map(|match_| match_.as_str())
.unwrap_or(&url)
.to_string();
if link_map.contains_key(&url) && !is_inside_code_block(caps, text) {
return format!(r#"<a href="{0}">{0}</a>"#, url);
return format!(r#"<a href="{0}">{1}</a>"#, url, link_text);
};
// Leave unchanged if post does not exist
caps[0].to_string()
@ -75,6 +79,7 @@ mod tests {
const TEXT_WITH_OBJECT_LINKS: &str = concat!(
"test [[https://example.org/1]] link ",
"test link with [[https://example.org/1|text]] ",
"test ([[https://example.org/2]])",
);
@ -95,6 +100,7 @@ mod tests {
let result = replace_object_links(&link_map, TEXT_WITH_OBJECT_LINKS);
let expected_result = concat!(
r#"test <a href="https://example.org/1">https://example.org/1</a> link "#,
r#"test link with <a href="https://example.org/1">text</a> "#,
r#"test (<a href="https://example.org/2">https://example.org/2</a>)"#,
);
assert_eq!(result, expected_result);