git » sdk » commit 4cd603b

Render links to text

author Stephen Paul Weber
2026-04-12 19:48:19 UTC
committer Stephen Paul Weber
2026-04-12 19:48:19 UTC
parent 437d031824b1aab59cd2eff0c8e09d4a978b9640

Render links to text

borogove/XEP0393.hx +15 -0
test/TestChatMessageBuilder.hx +27 -0

diff --git a/borogove/XEP0393.hx b/borogove/XEP0393.hx
index fe2714a..6e32cb3 100644
--- a/borogove/XEP0393.hx
+++ b/borogove/XEP0393.hx
@@ -66,6 +66,21 @@ class XEP0393 {
 			endsWithNewline = false;
 		}
 
+		if (xhtml.name == "a") {
+			final href = xhtml.attr.get("href") ?? "";
+			final textBuf = new StringBuf();
+			for (child in xhtml.children) {
+				final rendered = renderNode(child, inPre, endsWithNewline);
+				textBuf.add(rendered);
+				endsWithNewline = rendered.endsWith("\n");
+			}
+			final text = textBuf.toString();
+			if (text == href || href.endsWith(text)) {
+				return '<$href>';
+			}
+			return '$text <$href>';
+		}
+
 		for (child in xhtml.children) {
 			final rendered = renderNode(child, xhtml.name == "pre", endsWithNewline);
 			s.add(rendered);
diff --git a/test/TestChatMessageBuilder.hx b/test/TestChatMessageBuilder.hx
index 36793f9..7b4baaa 100644
--- a/test/TestChatMessageBuilder.hx
+++ b/test/TestChatMessageBuilder.hx
@@ -26,6 +26,33 @@ class TestChatMessageBuilder extends utest.Test {
 		);
 	}
 
+	public function testConvertHtmlToTextWithLink() {
+		final msg = new ChatMessageBuilder();
+		msg.setBody(Html.fromString("hello <a href='https://www.example.com/test'>there</a>"));
+		Assert.equals(
+			"hello there <https://www.example.com/test>",
+			msg.text
+		);
+	}
+
+	public function testConvertHtmlToTextWithLinkTextIsUrl() {
+		final msg = new ChatMessageBuilder();
+		msg.setBody(Html.fromString("hello <a href='https://www.example.com/test'>https://www.example.com/test</a>"));
+		Assert.equals(
+			"hello <https://www.example.com/test>",
+			msg.text
+		);
+	}
+
+	public function testConvertHtmlToTextWithLinkTextIsRedundant() {
+		final msg = new ChatMessageBuilder();
+		msg.setBody(Html.fromString("hello <a href='https://www.example.com/test'>example.com/test</a>"));
+		Assert.equals(
+			"hello <https://www.example.com/test>",
+			msg.text
+		);
+	}
+
 	public function testConvertHtmlToTextWithParas() {
 		final msg = new ChatMessageBuilder();
 		msg.setBody(Html.fromString("<blockquote>Hello<br>you</blockquote><img alt=':boop:'><br><b>hi</b> <em>hi</em> <s>hey</s> <tt>up</tt><p>a</p><p>b</p><pre>hello<br>you"));