BlueGit

ict rusty-teams

Files

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

mentions.rs

mentions.rs 14.5 KiB Download Raw
1use std::ops::Range;
2
3use graph::{MentionTarget, OutgoingMention};
4use serde::{Deserialize, Serialize};
5
6use crate::draft::{Draft, LineKind, MarkKind};
7use crate::error::{Error, Result};
8use crate::markdown::escape_html;
9
10/// `text` is the display name exactly as it appears after the `@` in the message text.
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub struct MentionInput {
13 pub target: MentionTarget,
14 pub text: String,
15}
16
17impl MentionInput {
18 pub fn user(user_id: &str, text: &str) -> Self {
19 MentionInput {
20 target: MentionTarget::User {
21 user_id: user_id.to_owned(),
22 },
23 text: text.to_owned(),
24 }
25 }
26
27 pub fn channel(channel_id: &str, text: &str) -> Self {
28 MentionInput {
29 target: MentionTarget::Channel {
30 channel_id: channel_id.to_owned(),
31 },
32 text: text.to_owned(),
33 }
34 }
35
36 pub fn team(team_id: &str, text: &str) -> Self {
37 MentionInput {
38 target: MentionTarget::Team {
39 team_id: team_id.to_owned(),
40 },
41 text: text.to_owned(),
42 }
43 }
44}
45
46fn same_char(expected: char, actual: char, ignore_case: bool) -> bool {
47 expected == actual || (ignore_case && expected.to_lowercase().eq(actual.to_lowercase()))
48}
49
50fn word_char(character: Option<char>) -> bool {
51 character.is_some_and(char::is_alphanumeric)
52}
53
54/// An `@` opens a mention only at the start, after whitespace or after opening punctuation: not in `ops@acme.com` or `medium.com/@ada`.
55fn opens_mention(before: Option<char>) -> bool {
56 before.is_none_or(|character| character.is_whitespace() || "([{\"'<,:;".contains(character))
57}
58
59/// Byte length of the text that spells `name`, compared character by character.
60fn spelled_len(text: &str, name: &str, ignore_case: bool) -> Option<usize> {
61 let mut characters = text.char_indices();
62 let mut length = 0;
63 for expected in name.chars() {
64 let (offset, actual) = characters.next()?;
65 if !same_char(expected, actual, ignore_case) {
66 return None;
67 }
68 length = offset + actual.len_utf8();
69 }
70 (length > 0).then_some(length)
71}
72
73fn in_plain_run(draft: &Draft, span: &Range<usize>) -> bool {
74 let marks_allow = draft.marks().iter().all(|mark| {
75 let touches = mark.range.start < span.end && span.start < mark.range.end;
76 !touches
77 || (!matches!(mark.kind, MarkKind::Link(_) | MarkKind::Code)
78 && mark.range.start <= span.start
79 && mark.range.end >= span.end)
80 });
81 let in_code_block = [span.start, span.end.saturating_sub(1)]
82 .into_iter()
83 .any(|offset| {
84 matches!(
85 draft.lines().get(draft.line_at(offset)),
86 Some(LineKind::Code(_))
87 )
88 });
89 marks_allow && !in_code_block
90}
91
92/// Every `@name` a mention may sit on: whole word on both sides, in plain text, not in a link, code or half-formatted.
93pub fn plain_mention_spans(draft: &Draft, name: &str, ignore_case: bool) -> Vec<Range<usize>> {
94 let text = draft.text();
95 text.match_indices('@')
96 .filter_map(|(start, _)| {
97 let end = start + 1 + spelled_len(&text[start + 1..], name, ignore_case)?;
98 let spans_ok = opens_mention(text[..start].chars().next_back())
99 && !word_char(text[end..].chars().next());
100 (spans_ok && in_plain_run(draft, &(start..end))).then_some(start..end)
101 })
102 .collect()
103}
104
105struct TextChar {
106 character: char,
107 start: usize,
108 end: usize,
109 plain: bool,
110}
111
112const NAMED_ENTITIES: [(&str, char); 4] = [
113 ("&amp;", '&'),
114 ("&lt;", '<'),
115 ("&gt;", '>'),
116 ("&quot;", '"'),
117];
118
119fn decode_entity(rest: &str) -> Option<(char, usize)> {
120 if let Some((entity, character)) = NAMED_ENTITIES
121 .iter()
122 .find(|(entity, _)| rest.starts_with(entity))
123 {
124 return Some((*character, entity.len()));
125 }
126 let numeric = rest.strip_prefix("&#")?;
127 let end = numeric.bytes().take(10).position(|byte| byte == b';')?;
128 let digits = &numeric[..end];
129 let code = match digits.strip_prefix(['x', 'X']) {
130 Some(hex) if !hex.is_empty() && hex.bytes().all(|byte| byte.is_ascii_hexdigit()) => {
131 u32::from_str_radix(hex, 16).ok()?
132 }
133 None if !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) => {
134 digits.parse().ok()?
135 }
136 _ => return None,
137 };
138 Some((char::from_u32(code)?, 2 + end + 1))
139}
140
141/// The characters of the text nodes with their HTML offsets; `plain` is false inside a, code and pre.
142fn text_characters(html: &str) -> Vec<TextChar> {
143 let mut characters = Vec::new();
144 let mut depth = 0usize;
145 let mut offset = 0;
146 while offset < html.len() {
147 let rest = &html[offset..];
148 if rest.starts_with('<')
149 && let Some(close) = rest.find('>')
150 {
151 let tag = rest[1..close].trim();
152 let closing = tag.starts_with('/');
153 let name: String = tag
154 .trim_start_matches('/')
155 .chars()
156 .take_while(|character| character.is_ascii_alphanumeric())
157 .collect::<String>()
158 .to_ascii_lowercase();
159 if matches!(name.as_str(), "a" | "code" | "pre") && !tag.ends_with('/') {
160 depth = if closing {
161 depth.saturating_sub(1)
162 } else {
163 depth + 1
164 };
165 }
166 offset += close + 1;
167 if matches!(
168 name.as_str(),
169 "br" | "p" | "div" | "li" | "ul" | "ol" | "blockquote" | "pre"
170 ) {
171 characters.push(TextChar {
172 character: ' ',
173 start: offset,
174 end: offset,
175 plain: true,
176 });
177 }
178 continue;
179 }
180 let (character, length) = decode_entity(rest).unwrap_or_else(|| {
181 let character = rest.chars().next().unwrap_or_default();
182 (character, character.len_utf8())
183 });
184 characters.push(TextChar {
185 character,
186 start: offset,
187 end: offset + length,
188 plain: depth == 0,
189 });
190 offset += length;
191 }
192 characters
193}
194
195fn spelled_at(characters: &[TextChar], at: usize, name: &[char]) -> bool {
196 let Some(span) = characters.get(at..at + 1 + name.len()) else {
197 return false;
198 };
199 span[0].character == '@'
200 && span
201 .iter()
202 .zip(std::iter::once(&'@').chain(name))
203 .all(|(found, expected)| found.character == *expected && found.plain)
204 && span.windows(2).all(|pair| pair[0].end == pair[1].start)
205 && opens_mention(at.checked_sub(1).map(|before| characters[before].character))
206 && !word_char(
207 characters
208 .get(at + 1 + name.len())
209 .map(|after| after.character),
210 )
211}
212
213/// Mentions are matched in order, each at the first `@text` after the previous one that sits in a plain text run (see `plain_mention_spans`). Unmatched mentions stay plain text.
214pub fn apply_mentions(html: &str, inputs: &[MentionInput]) -> (String, Vec<OutgoingMention>) {
215 let characters = text_characters(html);
216 let mut output = String::with_capacity(html.len());
217 let mut outgoing = Vec::new();
218 let mut cursor = 0;
219 let mut next_character = 0;
220 for input in inputs {
221 let name: Vec<char> = input.text.chars().collect();
222 let Some(at) = (next_character..characters.len())
223 .find(|at| !name.is_empty() && spelled_at(&characters, *at, &name))
224 else {
225 continue;
226 };
227 let last = &characters[at + name.len()];
228 let id = outgoing.len() as u32;
229 output.push_str(&html[cursor..characters[at].start]);
230 output.push_str(&format!(
231 "<at id=\"{id}\">{}</at>",
232 escape_html(&input.text)
233 ));
234 cursor = last.end;
235 next_character = at + name.len() + 1;
236 outgoing.push(OutgoingMention {
237 id,
238 text: input.text.clone(),
239 target: input.target.clone(),
240 });
241 }
242 output.push_str(&html[cursor..]);
243 (output, outgoing)
244}
245
246pub(crate) fn ensure_allowed_in_chat(inputs: &[MentionInput]) -> Result<()> {
247 if inputs
248 .iter()
249 .any(|input| !matches!(input.target, MentionTarget::User { .. }))
250 {
251 return Err(Error::Unsupported("a channel or team mention in a chat"));
252 }
253 Ok(())
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259
260 #[test]
261 fn mentions_become_at_tags_with_sequential_ids() {
262 let (html, mentions) = apply_mentions(
263 "hi @Ada Example and @Bo, see @General",
264 &[
265 MentionInput::user("u1", "Ada Example"),
266 MentionInput::user("u2", "Bo"),
267 MentionInput::channel("19:c", "General"),
268 ],
269 );
270 assert_eq!(
271 html,
272 "hi <at id=\"0\">Ada Example</at> and <at id=\"1\">Bo</at>, see <at id=\"2\">General</at>"
273 );
274 assert_eq!(
275 mentions
276 .iter()
277 .map(|mention| mention.id)
278 .collect::<Vec<_>>(),
279 [0, 1, 2]
280 );
281 }
282
283 fn spans(markdown: &str, name: &str, ignore_case: bool) -> Vec<String> {
284 let draft = Draft::from_markdown(markdown);
285 plain_mention_spans(&draft, name, ignore_case)
286 .into_iter()
287 .map(|span| draft.text()[span].to_owned())
288 .collect()
289 }
290
291 fn placed(markdown: &str, name: &str) -> usize {
292 let html = Draft::from_markdown(markdown).to_html();
293 apply_mentions(&html, &[MentionInput::user("u1", name)])
294 .1
295 .len()
296 }
297
298 #[test]
299 fn a_mention_never_matches_inside_a_longer_name_or_after_a_word() {
300 assert_eq!(spans("@Adam and @Ada!", "Ada", false), ["@Ada"]);
301 assert!(spans("@Adam", "Ada", false).is_empty());
302 assert!(spans("ops@Ada.example", "Ada", false).is_empty());
303 assert!(spans("mail ops@acme.com", "acme", false).is_empty());
304 assert_eq!(placed("ops@Ada x", "Ada"), 0);
305 assert_eq!(placed("@Adam then @Ada", "Ada"), 1);
306 }
307
308 #[test]
309 fn mentions_stay_out_of_links_code_and_half_formatted_names() {
310 for markdown in [
311 "[docs](https://example.com/@Ada)",
312 "see `@Ada` here",
313 "```\n@Ada\n```",
314 "read medium.com/@Ada today",
315 "@**Ada**",
316 "[@Ada](https://example.com)",
317 ] {
318 assert!(spans(markdown, "Ada", false).is_empty(), "{markdown}");
319 assert_eq!(placed(markdown, "Ada"), 0, "{markdown}");
320 }
321 for markdown in ["**@Ada** hi", "link https://example.com/@Ada and @Ada"] {
322 assert_eq!(spans(markdown, "Ada", false), ["@Ada"], "{markdown}");
323 assert_eq!(placed(markdown, "Ada"), 1, "{markdown}");
324 }
325 let html = Draft::from_markdown("https://example.com/@Ada then @Ada").to_html();
326 let (tagged, _) = apply_mentions(&html, &[MentionInput::user("u1", "Ada")]);
327 assert!(tagged.contains("example.com/@Ada"));
328 assert!(tagged.ends_with("then <at id=\"0\">Ada</at>"));
329 }
330
331 #[test]
332 fn mentions_after_line_breaks_and_block_edges_work_in_both_rules() {
333 for (markdown, name, expected) in [
334 ("Hi team\n@Ada please", "Ada", 1),
335 ("@Ada\nthanks", "Ada", 1),
336 ("- @Ada\n- @Bo", "Bo", 1),
337 ("- @Ada\n- @Bo", "Ada", 1),
338 ("> x\n@Ada", "Ada", 1),
339 ("@O'Brien hi", "O'Brien", 1),
340 ("say @\"Ada\" now", "\"Ada\"", 1),
341 ] {
342 assert_eq!(spans(markdown, name, false).len(), expected, "{markdown}");
343 assert_eq!(placed(markdown, name), expected, "{markdown}");
344 }
345 }
346
347 #[test]
348 fn numeric_entities_decode_like_named_ones() {
349 assert_eq!(decode_entity("&#x27;rest"), Some(('\'', 6)),);
350 assert_eq!(decode_entity("&#39;"), Some(('\'', 5)));
351 assert_eq!(decode_entity("&#zz;"), None);
352 assert_eq!(decode_entity("&#+39;"), None);
353 assert_eq!(decode_entity("&#x+27;"), None);
354 assert_eq!(decode_entity("&#-1;"), None);
355 assert_eq!(decode_entity("&#;"), None);
356 assert_eq!(decode_entity("&#1234567890123;"), None);
357 assert_eq!(decode_entity("&amp;"), Some(('&', 5)));
358 }
359
360 #[test]
361 fn case_insensitive_matching_keeps_offsets_after_wide_letters() {
362 let draft = Draft::from_markdown("\u{130} @ADA");
363 let found = plain_mention_spans(&draft, "ada", true);
364 assert_eq!(found.len(), 1);
365 assert_eq!(&draft.text()[found[0].clone()], "@ADA");
366 assert!(plain_mention_spans(&draft, "ada", false).is_empty());
367 }
368
369 #[test]
370 fn repeated_names_are_matched_left_to_right() {
371 let (html, mentions) = apply_mentions(
372 "@Ada then @Ada",
373 &[
374 MentionInput::user("u1", "Ada"),
375 MentionInput::user("u2", "Ada"),
376 ],
377 );
378 assert_eq!(html, "<at id=\"0\">Ada</at> then <at id=\"1\">Ada</at>");
379 assert_eq!(mentions.len(), 2);
380 }
381
382 #[test]
383 fn unmatched_mentions_are_dropped_and_ids_stay_dense() {
384 let (html, mentions) = apply_mentions(
385 "@Bo only",
386 &[
387 MentionInput::user("u1", "Ada"),
388 MentionInput::user("u2", "Bo"),
389 ],
390 );
391 assert_eq!(html, "<at id=\"0\">Bo</at> only");
392 assert_eq!(mentions.len(), 1);
393 assert_eq!(mentions[0].id, 0);
394 }
395
396 #[test]
397 fn names_are_html_escaped_like_the_body() {
398 let (html, mentions) = apply_mentions(
399 &crate::markdown_to_html("ping @Ada & Co <x>"),
400 &[MentionInput::user("u1", "Ada & Co")],
401 );
402 assert_eq!(html, "ping <at id=\"0\">Ada &amp; Co</at> &lt;x&gt;");
403 assert_eq!(mentions[0].text, "Ada & Co");
404 }
405
406 #[test]
407 fn mentions_inside_formatted_draft_html_become_at_tags() {
408 let (html, mentions) = apply_mentions(
409 &crate::Draft::from_markdown("**hi @Ada** and `@Bo`").to_html(),
410 &[MentionInput::user("u1", "Ada")],
411 );
412 assert_eq!(html, "<b>hi <at id=\"0\">Ada</at></b> and <code>@Bo</code>");
413 assert_eq!(mentions.len(), 1);
414 }
415
416 #[test]
417 fn chats_only_take_user_mentions() {
418 assert!(ensure_allowed_in_chat(&[MentionInput::user("u", "A")]).is_ok());
419 assert!(ensure_allowed_in_chat(&[MentionInput::team("t", "Squad")]).is_err());
420 }
421}