Add HTML classes to mention (#5475)

This commit is contained in:
flamingos-cant 2025-03-04 14:31:44 +00:00 committed by GitHub
parent 03630c8abd
commit 2f2f58da65
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 23 additions and 2 deletions

View file

@ -1,4 +1,12 @@
use markdown_it::{generics::inline::full_link, MarkdownIt, Node, NodeValue, Renderer};
use crate::utils::mention::MENTIONS_REGEX;
use markdown_it::{
generics::inline::full_link,
parser::inline::Text,
MarkdownIt,
Node,
NodeValue,
Renderer,
};
/// Renders markdown links. Copied directly from markdown-it source, unlike original code it also
/// sets `rel=nofollow` attribute.
@ -22,6 +30,14 @@ impl NodeValue for Link {
attrs.push(("title", title.clone()));
}
let text = node.children.first().and_then(|n| n.cast::<Text>());
if let Some(text) = text {
if MENTIONS_REGEX.is_match(&text.content) {
attrs.push(("class", "u-url".to_string()));
attrs.push(("class", "mention".to_string()));
}
}
fmt.open("a", &attrs);
fmt.contents(&node.children);
fmt.close("a");

View file

@ -133,6 +133,11 @@ mod tests {
<li id=\"fn1\" class=\"footnote-item\">\n\
<p>example.com <a href=\"#fnref1\" class=\"footnote-backref\">↩︎</a></p>\n\
</li>\n</ol>\n</section>\n"
),
(
"mention links",
"[@example@example.com](https://example.com/u/example)",
"<p><a href=\"https://example.com/u/example\" rel=\"nofollow\" class=\"u-url mention\">@example@example.com</a></p>\n"
)
];

View file

@ -3,7 +3,7 @@ use regex::Regex;
use std::sync::LazyLock;
#[allow(clippy::expect_used)]
static MENTIONS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
pub(crate) static MENTIONS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"@(?P<name>[\w.]+)@(?P<domain>[a-zA-Z0-9._:-]+)").expect("compile regex")
});
// TODO nothing is done with community / group webfingers yet, so just ignore those for now