BlueGit

ict rusty-teams

Files

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

mentions.rs

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