Commit b71ab48ec4

b71ab48ec4f815432fcdc04f317bac043b685984

parent: b59da8e87c

Unsigned

Darafei Praliaskouski <me@komzpa.net> · 2026-06-23 20:00 UTC
committer: <strk@kbt.io>

fix: render formatted Matrix HTML

Layout: unified · split

Cargo.lock +2
@@ -3302,6 +3302,7 @@ checksum = "6124d74847ea788601477c89a44485894432a806824cae93885c5825a8ae9dbc"
33023302dependencies = [
33033303 "as_variant",
33043304 "html5ever",
3305 "ruma-common",
33053306 "tracing",
33063307 "wildmatch",
33073308]
@@ -4705,6 +4706,7 @@ dependencies = [
47054706 "matrix-sdk",
47064707 "mime_guess",
47074708 "qrcode",
4709 "ruma-html",
47084710 "serde_json",
47094711 "strum",
47104712 "tokio",
Cargo.toml +1
@@ -44,6 +44,7 @@ tracing-subscriber = { version = "0.3.15", features = ["env-filter"] }
4444uuid = { version = "1.1.2", features = ["v4"] }
4545unicode-segmentation = "1.10.0"
4646futures-util = "0.3"
47ruma-html = { version = "0.5.0", features = ["matrix"] }
4748
4849# Auto-select version from matrix-sdk
4950qrcode = { version = "*", default-features = false }
src/render.rs +350 −15
@@ -39,6 +39,10 @@ use matrix_sdk::{
3939 TransactionId, UserId,
4040 },
4141};
42use ruma_html::{
43 matrix::{AnchorUri, MatrixElement},
44 Html, NodeData, NodeRef,
45};
4246
4347use weechat::{Prefix, Weechat};
4448
@@ -232,16 +236,11 @@ impl Render for TextMessageEventContent {
232236 type RenderContext = ();
233237
234238 fn render(&self, _: &Self::RenderContext) -> RenderedContent {
235 let lines = self
236 .body
237 .lines()
238 .map(|l| RenderedLine {
239 message: l.to_owned(),
240 tags: self.tags(),
241 })
242 .collect();
243 // TODO: parse and render using the formatted body.
244 RenderedContent { lines }
239 if let Some(body) = self.formatted_body() {
240 render_formatted_message_body(body, self.tags())
241 } else {
242 render_plain_message_body(self.body(), self.tags())
243 }
245244 }
246245}
247246
@@ -254,9 +253,13 @@ impl Render for EmoteMessageEventContent {
254253 }
255254
256255 fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
257 // TODO: parse and render using the formatted body.
258 // TODO: handle multiple lines in the body.
259 let message = format!("{} {}", sender.nick(), self.body);
256 let message = format!(
257 "{} {}",
258 sender.nick(),
259 self.formatted_body()
260 .map(formatted_body_to_plain_text)
261 .unwrap_or_else(|| self.body().to_owned())
262 );
260263
261264 let line = RenderedLine {
262265 message,
@@ -304,12 +307,13 @@ impl Render for NoticeMessageEventContent {
304307 }
305308
306309 fn render(&self, sender: &Self::RenderContext) -> RenderedContent {
307 // TODO: parse and render using the formatted body.
308310 let message = format!(
309311 "{color_notice}Notice\
310312 {color_delim}({color_reset}{}{color_delim}){color_reset}: {}",
311313 sender.nick(),
312 self.body,
314 self.formatted_body()
315 .map(formatted_body_to_plain_text)
316 .unwrap_or_else(|| self.body().to_owned()),
313317 color_notice = Weechat::color("irc.color.notice"),
314318 color_delim = Weechat::color("chat_delimiters"),
315319 color_reset = Weechat::color("reset"),
@@ -787,6 +791,275 @@ macro_rules! render_key_content {
787791render_key_content!(KeyVerificationKeyEventContent);
788792render_key_content!(ToDeviceKeyVerificationKeyEventContent);
789793
794fn render_formatted_message_body(
795 body: &str,
796 tags: Vec<String>,
797) -> RenderedContent {
798 render_plain_message_body(&formatted_body_to_plain_text(body), tags)
799}
800
801fn render_plain_message_body(body: &str, tags: Vec<String>) -> RenderedContent {
802 let lines = body
803 .lines()
804 .map(|l| RenderedLine {
805 message: l.to_owned(),
806 tags: tags.clone(),
807 })
808 .collect();
809
810 RenderedContent { lines }
811}
812
813fn formatted_body_to_plain_text(body: &str) -> String {
814 let html = Html::parse(body);
815 html.sanitize();
816
817 let mut output = String::new();
818 let mut context = HtmlRenderContext::default();
819
820 for node in html.children() {
821 render_html_node(&node, &mut output, &mut context);
822 }
823
824 trim_newlines(output)
825}
826
827#[derive(Clone, Default)]
828struct HtmlRenderContext {
829 lists: Vec<ListContext>,
830 in_pre: bool,
831}
832
833#[derive(Clone)]
834enum ListContext {
835 Unordered,
836 Ordered { next: i64 },
837}
838
839fn render_html_node(
840 node: &NodeRef,
841 output: &mut String,
842 context: &mut HtmlRenderContext,
843) {
844 match node.data() {
845 NodeData::Text(text) => output.push_str(&text.borrow()),
846 NodeData::Element(element) => match element.to_matrix().element {
847 MatrixElement::Br => push_newline(output),
848 MatrixElement::Hr => {
849 push_newline(output);
850 output.push_str("---");
851 push_newline(output);
852 }
853 MatrixElement::P
854 | MatrixElement::Div(_)
855 | MatrixElement::Details
856 | MatrixElement::Summary
857 | MatrixElement::Table
858 | MatrixElement::Thead
859 | MatrixElement::Tbody
860 | MatrixElement::Tr
861 | MatrixElement::Caption
862 | MatrixElement::H(_) => {
863 push_newline(output);
864 render_html_children(node, output, context);
865 push_newline(output);
866 }
867 MatrixElement::Blockquote => {
868 let mut quote = String::new();
869 let mut quote_context = context.clone();
870
871 render_html_children(node, &mut quote, &mut quote_context);
872
873 push_newline(output);
874 output.push_str(&prefix_lines(trim_newlines(quote), "> "));
875 push_newline(output);
876 }
877 MatrixElement::Ul => {
878 context.lists.push(ListContext::Unordered);
879 push_newline(output);
880 render_html_children(node, output, context);
881 context.lists.pop();
882 push_newline(output);
883 }
884 MatrixElement::Ol(ordered) => {
885 context.lists.push(ListContext::Ordered {
886 next: ordered.start.unwrap_or(1),
887 });
888 push_newline(output);
889 render_html_children(node, output, context);
890 context.lists.pop();
891 push_newline(output);
892 }
893 MatrixElement::Th | MatrixElement::Td => {
894 render_html_children(node, output, context);
895 output.push('\t');
896 }
897 MatrixElement::Li => {
898 push_newline(output);
899 output.push_str(
900 &" ".repeat(context.lists.len().saturating_sub(1)),
901 );
902 output.push_str(&list_marker(context));
903 render_html_children(node, output, context);
904 }
905 MatrixElement::A(anchor) => {
906 let start = output.len();
907 render_html_children(node, output, context);
908 if let Some(href) =
909 anchor.href.and_then(|href| anchor_uri_to_string(&href))
910 {
911 if output[start..].trim() != href {
912 output.push_str(" <");
913 output.push_str(&href);
914 output.push('>');
915 }
916 }
917 }
918 MatrixElement::B | MatrixElement::Strong => {
919 render_wrapped_html_children(node, output, context, "*");
920 }
921 MatrixElement::I | MatrixElement::Em => {
922 render_wrapped_html_children(node, output, context, "_");
923 }
924 MatrixElement::S | MatrixElement::Del => {
925 render_wrapped_html_children(node, output, context, "~");
926 }
927 MatrixElement::Code(_) if !context.in_pre => {
928 render_wrapped_html_children(node, output, context, "`");
929 }
930 MatrixElement::Pre => {
931 let was_in_pre = context.in_pre;
932 context.in_pre = true;
933
934 let mut code = String::new();
935 render_html_children(node, &mut code, context);
936
937 context.in_pre = was_in_pre;
938
939 push_newline(output);
940 output.push_str("```");
941 push_newline(output);
942 output.push_str(&trim_newlines(code));
943 push_newline(output);
944 output.push_str("```");
945 push_newline(output);
946 }
947 MatrixElement::Img(image) => {
948 if let Some(alt) = image.alt {
949 output.push_str(&alt);
950 } else if let Some(src) = image.src {
951 output.push_str(src.as_str());
952 }
953 }
954 MatrixElement::MatrixReply => {}
955 MatrixElement::Other(_) => {
956 render_html_children(node, output, context)
957 }
958 _ => render_html_children(node, output, context),
959 },
960 NodeData::Document | NodeData::Other => {
961 render_html_children(node, output, context)
962 }
963 }
964}
965
966fn render_html_children(
967 node: &NodeRef,
968 output: &mut String,
969 context: &mut HtmlRenderContext,
970) {
971 for child in node.children() {
972 render_html_node(&child, output, context);
973 }
974}
975
976fn render_wrapped_html_children(
977 node: &NodeRef,
978 output: &mut String,
979 context: &mut HtmlRenderContext,
980 wrapper: &str,
981) {
982 output.push_str(wrapper);
983 render_html_children(node, output, context);
984 output.push_str(wrapper);
985}
986
987fn list_marker(context: &mut HtmlRenderContext) -> String {
988 match context.lists.last_mut() {
989 Some(ListContext::Ordered { next }) => {
990 let marker = format!("{}. ", next);
991 *next += 1;
992 marker
993 }
994 _ => "- ".to_owned(),
995 }
996}
997
998fn anchor_uri_to_string(uri: &AnchorUri) -> Option<String> {
999 match uri {
1000 AnchorUri::Matrix(uri) => Some(uri.to_string()),
1001 AnchorUri::MatrixTo(uri) => Some(uri.to_string()),
1002 AnchorUri::Other(uri) => Some(uri.to_string()),
1003 _ => None,
1004 }
1005}
1006
1007fn prefix_lines(text: String, prefix: &str) -> String {
1008 text.lines()
1009 .map(|line| {
1010 if line.is_empty() {
1011 prefix.trim_end().to_owned()
1012 } else {
1013 format!("{prefix}{line}")
1014 }
1015 })
1016 .collect::<Vec<_>>()
1017 .join("\n")
1018}
1019
1020fn push_newline(output: &mut String) {
1021 if !output.ends_with('\n') {
1022 output.push('\n');
1023 }
1024}
1025
1026fn trim_newlines(mut output: String) -> String {
1027 while output.starts_with('\n') {
1028 output.remove(0);
1029 }
1030
1031 while output.ends_with('\n') {
1032 output.pop();
1033 }
1034
1035 output
1036}
1037
1038/// Trait for message event types that contain an optional formatted body.
1039trait HasFormattedBody {
1040 fn body(&self) -> &str;
1041 fn formatted_body(&self) -> Option<&str>;
1042}
1043
1044// Repeating this for each event type would get boring fast so lets use a simple
1045// macro to implement the trait for a struct that has a `body` and
1046// `formatted_body` field
1047macro_rules! has_formatted_body {
1048 ($content: ident) => {
1049 impl HasFormattedBody for $content {
1050 #[inline]
1051 fn body(&self) -> &str {
1052 &self.body
1053 }
1054
1055 #[inline]
1056 fn formatted_body(&self) -> Option<&str> {
1057 self.formatted.as_ref().map(|f| f.body.as_ref())
1058 }
1059 }
1060 };
1061}
1062
7901063/// This trait is implemented for message types that can contain either an URL
7911064/// or an encrypted file. One of these _must_ be present.
7921065pub trait HasUrlOrFile {
@@ -1072,6 +1345,18 @@ mod tests {
10721345 );
10731346 }
10741347
1348 #[test]
1349 fn formatted_body_plain_text_decodes_matrix_html() {
1350 let body = "<p>Hello <b>world</b> &amp; \
1351 <a href=\"https://example.org\">link</a></p>\
1352 <ul><li>one</li><li>two</li></ul>";
1353
1354 assert_eq!(
1355 "Hello *world* & link <https://example.org>\n- one\n- two",
1356 formatted_body_to_plain_text(body)
1357 );
1358 }
1359
10751360 #[test]
10761361 fn test_encrypted_media_has_no_plain_download_command() {
10771362 use std::collections::BTreeMap;
@@ -1147,4 +1432,54 @@ mod tests {
11471432 .contains(&"matrix_reply".to_owned()));
11481433 assert_eq!("reply body", rendered.content.lines[1].message);
11491434 }
1435
1436 #[test]
1437 fn formatted_body_plain_text_keeps_block_structure() {
1438 let body = "<blockquote><p>quoted</p><p>text</p></blockquote>\
1439 <ol start=\"3\"><li>three</li><li>four</li></ol>";
1440
1441 assert_eq!(
1442 "> quoted\n> text\n3. three\n4. four",
1443 formatted_body_to_plain_text(body)
1444 );
1445 }
1446
1447 #[test]
1448 fn formatted_body_plain_text_marks_code_and_emphasis() {
1449 let body = "<p><em>try</em> <code>cargo test</code></p>\
1450 <pre><code class=\"language-rust\">fn main() {}</code></pre>";
1451
1452 assert_eq!(
1453 "_try_ `cargo test`\n```\nfn main() {}\n```",
1454 formatted_body_to_plain_text(body)
1455 );
1456 }
1457
1458 #[test]
1459 fn formatted_body_plain_text_removes_reply_fallback() {
1460 let body = "<mx-reply><blockquote>old reply</blockquote></mx-reply>\
1461 <p>new message</p>";
1462
1463 assert_eq!("new message", formatted_body_to_plain_text(body));
1464 }
1465
1466 #[test]
1467 fn text_render_uses_formatted_body_when_available() {
1468 let content =
1469 TextMessageEventContent::html("fallback", "<p>Hello<br>world</p>");
1470 let rendered = content.render(&());
1471
1472 assert_eq!(rendered.lines.len(), 2);
1473 assert_eq!(rendered.lines[0].message, "Hello");
1474 assert_eq!(rendered.lines[1].message, "world");
1475 }
1476
1477 #[test]
1478 fn text_render_keeps_plain_body_plain() {
1479 let content = TextMessageEventContent::plain("literal <b> text");
1480 let rendered = content.render(&());
1481
1482 assert_eq!(rendered.lines.len(), 1);
1483 assert_eq!(rendered.lines[0].message, "literal <b> text");
1484 }
11501485}