BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / mentions.rs

mentions.rs

mentions.rs 4.8 KiB Download Raw
1use graph::{MentionTarget, OutgoingMention};
2use serde::{Deserialize, Serialize};
3
4use crate::error::{Error, Result};
5use crate::markdown::escape_html;
6
7/// `text` is the display name exactly as it appears after the `@` in the message text.
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
9pub struct MentionInput {
10 pub target: MentionTarget,
11 pub text: String,
12}
13
14impl MentionInput {
15 pub fn user(user_id: &str, text: &str) -> Self {
16 MentionInput {
17 target: MentionTarget::User {
18 user_id: user_id.to_owned(),
19 },
20 text: text.to_owned(),
21 }
22 }
23
24 pub fn channel(channel_id: &str, text: &str) -> Self {
25 MentionInput {
26 target: MentionTarget::Channel {
27 channel_id: channel_id.to_owned(),
28 },
29 text: text.to_owned(),
30 }
31 }
32
33 pub fn team(team_id: &str, text: &str) -> Self {
34 MentionInput {
35 target: MentionTarget::Team {
36 team_id: team_id.to_owned(),
37 },
38 text: text.to_owned(),
39 }
40 }
41}
42
43/// Mentions are matched in order, each at the first `@text` after the previous one. Unmatched mentions stay plain text.
44pub(crate) fn apply_mentions(
45 html: &str,
46 inputs: &[MentionInput],
47) -> (String, Vec<OutgoingMention>) {
48 let mut output = String::with_capacity(html.len());
49 let mut outgoing = Vec::new();
50 let mut cursor = 0;
51 for input in inputs {
52 let escaped = escape_html(&input.text);
53 let needle = format!("@{escaped}");
54 let Some(offset) = html[cursor..].find(&needle) else {
55 continue;
56 };
57 let id = outgoing.len() as u32;
58 output.push_str(&html[cursor..cursor + offset]);
59 output.push_str(&format!("<at id=\"{id}\">{escaped}</at>"));
60 cursor += offset + needle.len();
61 outgoing.push(OutgoingMention {
62 id,
63 text: input.text.clone(),
64 target: input.target.clone(),
65 });
66 }
67 output.push_str(&html[cursor..]);
68 (output, outgoing)
69}
70
71pub(crate) fn ensure_allowed_in_chat(inputs: &[MentionInput]) -> Result<()> {
72 if inputs
73 .iter()
74 .any(|input| !matches!(input.target, MentionTarget::User { .. }))
75 {
76 return Err(Error::Unsupported("a channel or team mention in a chat"));
77 }
78 Ok(())
79}
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84
85 #[test]
86 fn mentions_become_at_tags_with_sequential_ids() {
87 let (html, mentions) = apply_mentions(
88 "hi @Ada Example and @Bo, see @General",
89 &[
90 MentionInput::user("u1", "Ada Example"),
91 MentionInput::user("u2", "Bo"),
92 MentionInput::channel("19:c", "General"),
93 ],
94 );
95 assert_eq!(
96 html,
97 "hi <at id=\"0\">Ada Example</at> and <at id=\"1\">Bo</at>, see <at id=\"2\">General</at>"
98 );
99 assert_eq!(
100 mentions
101 .iter()
102 .map(|mention| mention.id)
103 .collect::<Vec<_>>(),
104 [0, 1, 2]
105 );
106 }
107
108 #[test]
109 fn repeated_names_are_matched_left_to_right() {
110 let (html, mentions) = apply_mentions(
111 "@Ada then @Ada",
112 &[
113 MentionInput::user("u1", "Ada"),
114 MentionInput::user("u2", "Ada"),
115 ],
116 );
117 assert_eq!(html, "<at id=\"0\">Ada</at> then <at id=\"1\">Ada</at>");
118 assert_eq!(mentions.len(), 2);
119 }
120
121 #[test]
122 fn unmatched_mentions_are_dropped_and_ids_stay_dense() {
123 let (html, mentions) = apply_mentions(
124 "@Bo only",
125 &[
126 MentionInput::user("u1", "Ada"),
127 MentionInput::user("u2", "Bo"),
128 ],
129 );
130 assert_eq!(html, "<at id=\"0\">Bo</at> only");
131 assert_eq!(mentions.len(), 1);
132 assert_eq!(mentions[0].id, 0);
133 }
134
135 #[test]
136 fn names_are_html_escaped_like_the_body() {
137 let (html, mentions) = apply_mentions(
138 &crate::markdown_to_html("ping @Ada & Co <x>"),
139 &[MentionInput::user("u1", "Ada & Co")],
140 );
141 assert_eq!(html, "ping <at id=\"0\">Ada &amp; Co</at> &lt;x&gt;");
142 assert_eq!(mentions[0].text, "Ada & Co");
143 }
144
145 #[test]
146 fn mentions_inside_formatted_draft_html_become_at_tags() {
147 let (html, mentions) = apply_mentions(
148 &crate::Draft::from_markdown("**hi @Ada** and `@Bo`").to_html(),
149 &[MentionInput::user("u1", "Ada")],
150 );
151 assert_eq!(html, "<b>hi <at id=\"0\">Ada</at></b> and <code>@Bo</code>");
152 assert_eq!(mentions.len(), 1);
153 }
154
155 #[test]
156 fn chats_only_take_user_mentions() {
157 assert!(ensure_allowed_in_chat(&[MentionInput::user("u", "A")]).is_ok());
158 assert!(ensure_allowed_in_chat(&[MentionInput::team("t", "Squad")]).is_err());
159 }
160}