Commit 290ed8febd

290ed8febd3b10b7954ffc2394218bd40dbbb212

parent: 72ef50f3ac

Unsigned

Darafei Praliaskouski <me@komzpa.net> · 2026-07-19 14:20 UTC
committer: <strk@kbt.io>

fix: include reply fallback text in context

Render the Matrix rich-reply fallback body in the reply context line when it is already present, while still removing that fallback from the visible message body.

Also remove the duplicate KeyVerificationDone match arm and unused Members::room helper reported in #203.

Layout: unified · split

src/render.rs +334 −56
@@ -41,7 +41,7 @@ use matrix_sdk::{
4141};
4242use ruma_html::{
4343 matrix::{AnchorUri, MatrixElement},
44 Html, NodeData, NodeRef,
44 Html, NodeData, NodeRef, SanitizerConfig,
4545};
4646
4747use weechat::{Prefix, Weechat};
@@ -82,6 +82,26 @@ impl RenderedEvent {
8282 event_id: &EventId,
8383 sender: Option<&str>,
8484 ) -> Self {
85 let reply_fallback = self.content.reply_fallback.take();
86 let reply_sender = sender
87 .map(ToOwned::to_owned)
88 .or_else(|| {
89 reply_fallback
90 .as_ref()
91 .and_then(|fallback| fallback.sender.clone())
92 })
93 .unwrap_or_else(|| event_id.as_str().to_owned());
94 let message = match reply_fallback {
95 Some(fallback) => {
96 format!(
97 "Reply to {}: {}",
98 reply_sender,
99 compact_reply_preview(&fallback.body)
100 )
101 }
102 None => format!("Reply to {}", reply_sender),
103 };
104
85105 let mut tags = self
86106 .content
87107 .lines
@@ -90,16 +110,7 @@ impl RenderedEvent {
90110 .unwrap_or_default();
91111 tags.push("matrix_reply".to_owned());
92112
93 self.content.lines.insert(
94 0,
95 RenderedLine {
96 tags,
97 message: format!(
98 "Reply to {}",
99 sender.unwrap_or_else(|| event_id.as_str())
100 ),
101 },
102 );
113 self.content.lines.insert(0, RenderedLine { tags, message });
103114
104115 self
105116 }
@@ -117,6 +128,30 @@ pub struct RenderedLine {
117128pub struct RenderedContent {
118129 /// The collection of lines that the event has.
119130 pub lines: Vec<RenderedLine>,
131 reply_fallback: Option<ReplyFallback>,
132}
133
134impl RenderedContent {
135 fn new(lines: Vec<RenderedLine>) -> Self {
136 Self {
137 lines,
138 reply_fallback: None,
139 }
140 }
141
142 fn with_reply_fallback(
143 mut self,
144 reply_fallback: Option<ReplyFallback>,
145 ) -> Self {
146 self.reply_fallback = reply_fallback;
147 self
148 }
149}
150
151#[derive(Clone, Debug)]
152struct ReplyFallback {
153 sender: Option<String>,
154 body: String,
120155}
121156
122157/// Trait allowing events to be rendered for Weechat.
@@ -266,7 +301,7 @@ impl Render for EmoteMessageEventContent {
266301 tags: self.tags(),
267302 };
268303
269 RenderedContent { lines: vec![line] }
304 RenderedContent::new(vec![line])
270305 }
271306}
272307
@@ -294,7 +329,7 @@ impl Render for LocationMessageEventContent {
294329 tags: self.tags(),
295330 };
296331
297 RenderedContent { lines: vec![line] }
332 RenderedContent::new(vec![line])
298333 }
299334}
300335
@@ -324,7 +359,7 @@ impl Render for NoticeMessageEventContent {
324359 tags: self.tags(),
325360 };
326361
327 RenderedContent { lines: vec![line] }
362 RenderedContent::new(vec![line])
328363 }
329364}
330365
@@ -352,7 +387,7 @@ impl Render for ServerNoticeMessageEventContent {
352387 tags: self.tags(),
353388 };
354389
355 RenderedContent { lines: vec![line] }
390 RenderedContent::new(vec![line])
356391 }
357392}
358393
@@ -493,7 +528,7 @@ impl<C: HasUrlOrFile> Render for C {
493528 tags: self.tags(),
494529 };
495530
496 RenderedContent { lines: vec![line] }
531 RenderedContent::new(vec![line])
497532 }
498533}
499534
@@ -517,7 +552,7 @@ impl Render for RoomEncryptedEventContent {
517552 tags: self.tags(),
518553 };
519554
520 RenderedContent { lines: vec![line] }
555 RenderedContent::new(vec![line])
521556 }
522557}
523558
@@ -541,7 +576,7 @@ impl Render for RedactedSyncMessageLikeEvent<RedactedRoomMessageEventContent> {
541576 tags: self.tags(),
542577 };
543578
544 RenderedContent { lines: vec![line] }
579 RenderedContent::new(vec![line])
545580 }
546581}
547582
@@ -590,9 +625,7 @@ macro_rules! render_start_content {
590625 // We auto accept emoji verifications that start
591626 // from a verification request, so don't print
592627 // anything.
593 return RenderedContent {
594 lines: vec![],
595 }
628 return RenderedContent::new(vec![]);
596629 } else {
597630 format!(
598631 "You have started an interactive emoji \
@@ -617,9 +650,7 @@ macro_rules! render_start_content {
617650 // We auto accept emoji verifications that start
618651 // from a verification request, so don't print
619652 // anything.
620 return RenderedContent {
621 lines: vec![],
622 }
653 return RenderedContent::new(vec![]);
623654 }
624655 }
625656 }
@@ -636,12 +667,10 @@ macro_rules! render_start_content {
636667 _ => unreachable!(),
637668 };
638669
639 RenderedContent {
640 lines: vec![RenderedLine {
670 RenderedContent::new(vec![RenderedLine {
641671 message,
642672 tags: self.tags(),
643 }],
644 }
673 }])
645674 }
646675 }
647676 };
@@ -686,12 +715,10 @@ macro_rules! render_request_content {
686715 }
687716 };
688717
689 RenderedContent {
690 lines: vec![RenderedLine {
691 message,
692 tags: self.tags(),
693 }],
694 }
718 RenderedContent::new(vec![RenderedLine {
719 message,
720 tags: self.tags(),
721 }])
695722 }
696723 }
697724 };
@@ -723,12 +750,10 @@ macro_rules! render_ready_content {
723750 )
724751 };
725752
726 RenderedContent {
727 lines: vec![RenderedLine {
728 message,
729 tags: self.tags(),
730 }],
731 }
753 RenderedContent::new(vec![RenderedLine {
754 message,
755 tags: self.tags(),
756 }])
732757 }
733758 }
734759 };
@@ -782,7 +807,7 @@ macro_rules! render_key_content {
782807 })
783808 .collect();
784809
785 RenderedContent { lines }
810 RenderedContent::new(lines)
786811 }
787812 }
788813 };
@@ -795,7 +820,10 @@ fn render_formatted_message_body(
795820 body: &str,
796821 tags: Vec<String>,
797822) -> RenderedContent {
798 render_plain_message_body(&formatted_body_to_plain_text(body), tags)
823 let body = formatted_message_body_to_plain_text(body);
824
825 render_plain_message_body(&body.text, tags)
826 .with_reply_fallback(body.reply_fallback)
799827}
800828
801829fn render_plain_message_body(body: &str, tags: Vec<String>) -> RenderedContent {
@@ -807,11 +835,30 @@ fn render_plain_message_body(body: &str, tags: Vec<String>) -> RenderedContent {
807835 })
808836 .collect();
809837
810 RenderedContent { lines }
838 RenderedContent::new(lines)
811839}
812840
813841fn formatted_body_to_plain_text(body: &str) -> String {
842 formatted_message_body_to_plain_text(body).text
843}
844
845struct FormattedMessageBody {
846 text: String,
847 reply_fallback: Option<ReplyFallback>,
848}
849
850fn formatted_message_body_to_plain_text(body: &str) -> FormattedMessageBody {
814851 let html = Html::parse(body);
852 html.sanitize_with(&SanitizerConfig::compat());
853
854 let mut reply_fallback = None;
855
856 for node in html.children() {
857 if reply_fallback.is_none() {
858 reply_fallback = render_reply_fallback(&node);
859 }
860 }
861
815862 html.sanitize();
816863
817864 let mut output = String::new();
@@ -821,7 +868,10 @@ fn formatted_body_to_plain_text(body: &str) -> String {
821868 render_html_node(&node, &mut output, &mut context);
822869 }
823870
824 trim_newlines(output)
871 FormattedMessageBody {
872 text: trim_newlines(output),
873 reply_fallback,
874 }
825875}
826876
827877#[derive(Clone, Default)]
@@ -963,6 +1013,158 @@ fn render_html_node(
9631013 }
9641014}
9651015
1016fn render_reply_fallback(node: &NodeRef) -> Option<ReplyFallback> {
1017 let reply_node = find_first_matrix_reply(node)?;
1018 let blockquote = find_first_blockquote(&reply_node)?;
1019 let body = render_reply_fallback_body(&blockquote);
1020
1021 if body.is_empty() {
1022 return None;
1023 }
1024
1025 Some(ReplyFallback {
1026 sender: render_reply_fallback_sender(&blockquote),
1027 body,
1028 })
1029}
1030
1031fn find_first_matrix_reply(node: &NodeRef) -> Option<NodeRef> {
1032 if is_matrix_element(node, |element| {
1033 matches!(element, MatrixElement::MatrixReply)
1034 }) {
1035 return Some(node.clone());
1036 }
1037
1038 node.children()
1039 .find_map(|child| find_first_matrix_reply(&child))
1040}
1041
1042fn find_first_blockquote(node: &NodeRef) -> Option<NodeRef> {
1043 if is_matrix_element(node, |element| {
1044 matches!(element, MatrixElement::Blockquote)
1045 }) {
1046 return Some(node.clone());
1047 }
1048
1049 node.children()
1050 .find_map(|child| find_first_blockquote(&child))
1051}
1052
1053fn is_matrix_element<F>(node: &NodeRef, predicate: F) -> bool
1054where
1055 F: FnOnce(MatrixElement) -> bool,
1056{
1057 match node.data() {
1058 NodeData::Element(element) => predicate(element.to_matrix().element),
1059 _ => false,
1060 }
1061}
1062
1063fn render_reply_fallback_sender(blockquote: &NodeRef) -> Option<String> {
1064 let mut anchors = Vec::new();
1065
1066 collect_anchor_text_before_first_br(blockquote, &mut anchors);
1067
1068 anchors
1069 .into_iter()
1070 .filter_map(|anchor| {
1071 let anchor = collapse_whitespace(&anchor);
1072 (!anchor.is_empty() && !anchor.eq_ignore_ascii_case("in reply to"))
1073 .then_some(anchor)
1074 })
1075 .next_back()
1076}
1077
1078fn collect_anchor_text_before_first_br(
1079 node: &NodeRef,
1080 anchors: &mut Vec<String>,
1081) -> bool {
1082 match node.data() {
1083 NodeData::Element(element)
1084 if matches!(element.to_matrix().element, MatrixElement::Br) =>
1085 {
1086 return true;
1087 }
1088 NodeData::Element(element)
1089 if matches!(element.to_matrix().element, MatrixElement::A(_)) =>
1090 {
1091 let text = plain_text_children(node);
1092 if !text.trim().is_empty() {
1093 anchors.push(text);
1094 }
1095 }
1096 _ => {}
1097 }
1098
1099 for child in node.children() {
1100 if collect_anchor_text_before_first_br(&child, anchors) {
1101 return true;
1102 }
1103 }
1104
1105 false
1106}
1107
1108fn plain_text_children(node: &NodeRef) -> String {
1109 let mut text = String::new();
1110
1111 collect_plain_text(node, &mut text);
1112
1113 text
1114}
1115
1116fn collect_plain_text(node: &NodeRef, output: &mut String) {
1117 match node.data() {
1118 NodeData::Text(text) => output.push_str(&text.borrow()),
1119 _ => {
1120 for child in node.children() {
1121 collect_plain_text(&child, output);
1122 }
1123 }
1124 }
1125}
1126
1127fn render_reply_fallback_body(blockquote: &NodeRef) -> String {
1128 let mut output = String::new();
1129 let mut context = HtmlRenderContext::default();
1130 let mut after_intro = false;
1131
1132 for child in blockquote.children() {
1133 render_after_first_br(
1134 &child,
1135 &mut output,
1136 &mut context,
1137 &mut after_intro,
1138 );
1139 }
1140
1141 trim_newlines(output)
1142}
1143
1144fn render_after_first_br(
1145 node: &NodeRef,
1146 output: &mut String,
1147 context: &mut HtmlRenderContext,
1148 after_intro: &mut bool,
1149) {
1150 if !*after_intro {
1151 if is_matrix_element(node, |element| {
1152 matches!(element, MatrixElement::Br)
1153 }) {
1154 *after_intro = true;
1155 return;
1156 }
1157
1158 for child in node.children() {
1159 render_after_first_br(&child, output, context, after_intro);
1160 }
1161
1162 return;
1163 }
1164
1165 render_html_node(node, output, context);
1166}
1167
9661168fn render_html_children(
9671169 node: &NodeRef,
9681170 output: &mut String,
@@ -1004,6 +1206,28 @@ fn anchor_uri_to_string(uri: &AnchorUri) -> Option<String> {
10041206 }
10051207}
10061208
1209fn compact_reply_preview(body: &str) -> String {
1210 const MAX_PREVIEW_CHARS: usize = 160;
1211
1212 let body = collapse_whitespace(body);
1213
1214 if body.chars().count() <= MAX_PREVIEW_CHARS {
1215 return body;
1216 }
1217
1218 let mut preview = body
1219 .chars()
1220 .take(MAX_PREVIEW_CHARS.saturating_sub(3))
1221 .collect::<String>();
1222 preview.push_str("...");
1223
1224 preview
1225}
1226
1227fn collapse_whitespace(body: &str) -> String {
1228 body.split_whitespace().collect::<Vec<_>>().join(" ")
1229}
1230
10071231fn prefix_lines(text: String, prefix: &str) -> String {
10081232 text.lines()
10091233 .map(|line| {
@@ -1397,12 +1621,10 @@ mod tests {
13971621 let rendered = RenderedEvent {
13981622 message_timestamp: 0,
13991623 prefix: "alice\t".to_owned(),
1400 content: RenderedContent {
1401 lines: vec![RenderedLine {
1402 tags: vec!["matrix_text".to_owned()],
1403 message: "reply body".to_owned(),
1404 }],
1405 },
1624 content: RenderedContent::new(vec![RenderedLine {
1625 tags: vec!["matrix_text".to_owned()],
1626 message: "reply body".to_owned(),
1627 }]),
14061628 }
14071629 .add_reply_context(&event_id, Some("Alice"));
14081630
@@ -1421,12 +1643,10 @@ mod tests {
14211643 let rendered = RenderedEvent {
14221644 message_timestamp: 0,
14231645 prefix: "alice\t".to_owned(),
1424 content: RenderedContent {
1425 lines: vec![RenderedLine {
1426 tags: vec!["matrix_text".to_owned()],
1427 message: "reply body".to_owned(),
1428 }],
1429 },
1646 content: RenderedContent::new(vec![RenderedLine {
1647 tags: vec!["matrix_text".to_owned()],
1648 message: "reply body".to_owned(),
1649 }]),
14301650 }
14311651 .add_reply_context(&event_id, None);
14321652
@@ -1440,6 +1660,64 @@ mod tests {
14401660 assert_eq!("reply body", rendered.content.lines[1].message);
14411661 }
14421662
1663 #[test]
1664 fn reply_context_uses_formatted_reply_fallback_preview() {
1665 let event_id =
1666 matrix_sdk::ruma::owned_event_id!("$replyevent:example.org");
1667 let body = "\
1668 <mx-reply>\
1669 <blockquote>\
1670 <a href=\"https://matrix.to/#/!room:example.org/$replyevent:example.org\">In reply to</a> \
1671 <a href=\"https://matrix.to/#/@alice:example.org\">@alice:example.org</a>\
1672 <br>\
1673 <p>Previous <strong>message</strong> text</p>\
1674 </blockquote>\
1675 </mx-reply>\
1676 <p>new message</p>";
1677 let content = TextMessageEventContent::html("fallback", body);
1678 let rendered = RenderedEvent {
1679 message_timestamp: 0,
1680 prefix: "bob\t".to_owned(),
1681 content: content.render(&()),
1682 }
1683 .add_reply_context(&event_id, Some("Alice"));
1684
1685 assert_eq!(2, rendered.content.lines.len());
1686 assert_eq!(
1687 "Reply to Alice: Previous *message* text",
1688 rendered.content.lines[0].message
1689 );
1690 assert_eq!("new message", rendered.content.lines[1].message);
1691 }
1692
1693 #[test]
1694 fn reply_context_uses_reply_fallback_sender_when_local_sender_is_unknown() {
1695 let event_id =
1696 matrix_sdk::ruma::owned_event_id!("$replyevent:example.org");
1697 let body = "\
1698 <mx-reply>\
1699 <blockquote>\
1700 <a href=\"https://matrix.to/#/!room:example.org/$replyevent:example.org\">In reply to</a> \
1701 <a href=\"https://matrix.to/#/@alice:example.org\">@alice:example.org</a>\
1702 <br>\
1703 Previous message\
1704 </blockquote>\
1705 </mx-reply>\
1706 <p>new message</p>";
1707 let content = TextMessageEventContent::html("fallback", body);
1708 let rendered = RenderedEvent {
1709 message_timestamp: 0,
1710 prefix: "bob\t".to_owned(),
1711 content: content.render(&()),
1712 }
1713 .add_reply_context(&event_id, None);
1714
1715 assert_eq!(
1716 "Reply to @alice:example.org: Previous message",
1717 rendered.content.lines[0].message
1718 );
1719 }
1720
14431721 #[test]
14441722 fn formatted_body_plain_text_keeps_block_structure() {
14451723 let body = "<blockquote><p>quoted</p><p>text</p></blockquote>\
src/room/members.rs −4
@@ -271,10 +271,6 @@ impl Members {
271271 }
272272 }
273273
274 fn room(&self) -> &Room {
275 &self.room
276 }
277
278274 pub fn mark_active(
279275 &self,
280276 user_id: &UserId,
src/server.rs −3
@@ -916,9 +916,6 @@ impl InnerServer {
916916 refresh_status_bar = true;
917917 handle_event(&event, e.content.transaction_id.to_string()).await
918918 }
919 AnyToDeviceEvent::KeyVerificationDone(e) => {
920 handle_event(&event, e.content.transaction_id.to_string()).await
921 }
922919 _ => {}
923920 }
924921