fix(chat): render multi-word mentions as one mention
Teams sends one <at id> per word of a mention ("Tip of the day" tag,
two-word user names). Adjacent mentions separated only by whitespace
that point at the same user, app, tag or conversation now merge into
one, in the message view, copy text and when editing an own message.
Stored messages from before this change merge user mentions by position.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -474,7 +474,7 @@ fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mu
474
474
Some(url.as_str()),
475
475
out,
476
476
),
477
Span::Mention { name } => {
477
Span::Mention { name, .. } => {
478
478
let label = format!("@{}", name.trim_start_matches('@'));
479
479
out.push(
480
480
&label,
@@ -690,10 +690,14 @@ mod tests {
690
690
#[test]
691
691
fn mention_gets_an_at_sign_once() {
692
692
let blocks = layout_blocks(&[
693
Span::Mention { name: "Ada".into() },
693
Span::Mention {
694
name: "Ada".into(),
695
id: None,
696
},
694
697
text(" "),
695
698
Span::Mention {
696
699
name: "@Bob".into(),
700
id: None,
697
701
},
698
702
]);
699
703
let Block::Paragraph(inline) = &blocks[0] else {
@@ -474,7 +474,7 @@ fn append_inline(spans: &[Span], style: StyleFlags, link: Option<&str>, out: &mu474
Some(url.as_str()),474
Some(url.as_str()),475
out,475
out,476
),476
),477
Span::Mention { name } => {477
Span::Mention { name, .. } => {478
let label = format!("@{}", name.trim_start_matches('@'));478
let label = format!("@{}", name.trim_start_matches('@'));479
out.push(479
out.push(480
&label,480
&label,@@ -690,10 +690,14 @@ mod tests {690
#[test]690
#[test]691
fn mention_gets_an_at_sign_once() {691
fn mention_gets_an_at_sign_once() {692
let blocks = layout_blocks(&[692
let blocks = layout_blocks(&[693
Span::Mention { name: "Ada".into() },693
Span::Mention {694
name: "Ada".into(),695
id: None,696
},694
text(" "),697
text(" "),695
Span::Mention {698
Span::Mention {696
name: "@Bob".into(),699
name: "@Bob".into(),700
id: None,697
},701
},698
]);702
]);699
let Block::Paragraph(inline) = &blocks[0] else {703
let Block::Paragraph(inline) = &blocks[0] else {@@ -16,7 +16,7 @@ use gpui_kit::component::{
16
16
use gpui_kit::prelude::FluentBuilder as _;
17
17
use gpui_kit::*;
18
18
use store::MessageRecord;
19
use teams_core::{FileCard, ImageRef, MentionInput};
19
use teams_core::{FileCard, ImageRef};
20
20
21
21
use super::attachments::FileActions;
22
22
use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
@@ -1924,13 +1924,7 @@ impl ConversationView {
1924
1924
Some(Selection::Chat(_))
1925
1925
);
1926
1926
let mentions = if in_chat {
1927
teams_core::mentions(&record)
1928
.into_iter()
1929
.filter_map(|mention| {
1930
let user_id = mention.user_id?;
1931
Some(MentionInput::user(&user_id, &mention.name))
1932
})
1933
.collect()
1927
teams_core::user_mention_inputs(&record)
1934
1928
} else {
1935
1929
Vec::new()
1936
1930
};
@@ -16,7 +16,7 @@ use gpui_kit::component::{16
use gpui_kit::prelude::FluentBuilder as _;16
use gpui_kit::prelude::FluentBuilder as _;17
use gpui_kit::*;17
use gpui_kit::*;18
use store::MessageRecord;18
use store::MessageRecord;19
use teams_core::{FileCard, ImageRef, MentionInput};19
use teams_core::{FileCard, ImageRef};20
20
21
use super::attachments::FileActions;21
use super::attachments::FileActions;22
use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};22
use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};@@ -1924,13 +1924,7 @@ impl ConversationView {1924
Some(Selection::Chat(_))1924
Some(Selection::Chat(_))1925
);1925
);1926
let mentions = if in_chat {1926
let mentions = if in_chat {1927
teams_core::mentions(&record)1927
teams_core::user_mention_inputs(&record)1928
.into_iter()1929
.filter_map(|mention| {1930
let user_id = mention.user_id?;1931
Some(MentionInput::user(&user_id, &mention.name))1932
})1933
.collect()1934
} else {1928
} else {1935
Vec::new()1929
Vec::new()1936
};1930
};@@ -1667,7 +1667,7 @@ impl SpanLines {
1667
1667
Span::Link { url, children } => {
1668
1668
self.walk(children, kind, &with(MarkKind::Link(url.clone())))
1669
1669
}
1670
Span::Mention { name } => {
1670
Span::Mention { name, .. } => {
1671
1671
self.append(&format!("@{}", name.trim_start_matches('@')), kind, marks)
1672
1672
}
1673
1673
Span::LineBreak | Span::Rule if !self.open || block_follows => {}
@@ -1667,7 +1667,7 @@ impl SpanLines {1667
Span::Link { url, children } => {1667
Span::Link { url, children } => {1668
self.walk(children, kind, &with(MarkKind::Link(url.clone())))1668
self.walk(children, kind, &with(MarkKind::Link(url.clone())))1669
}1669
}1670
Span::Mention { name } => {1670
Span::Mention { name, .. } => {1671
self.append(&format!("@{}", name.trim_start_matches('@')), kind, marks)1671
self.append(&format!("@{}", name.trim_start_matches('@')), kind, marks)1672
}1672
}1673
Span::LineBreak | Span::Rule if !self.open || block_follows => {}1673
Span::LineBreak | Span::Rule if !self.open || block_follows => {}@@ -51,5 +51,5 @@ pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
51
51
pub use stored::{
52
52
AttachmentInfo, FileCard, FileKind, ImageRef, MentionInfo, QuoteInfo, ReactionInfo,
53
53
attachments, can_delete, can_edit, copy_text, files, images, mentions, message_spans, quotes,
54
reactions,
54
reactions, user_mention_inputs,
55
55
};
@@ -51,5 +51,5 @@ pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};51
pub use stored::{51
pub use stored::{52
AttachmentInfo, FileCard, FileKind, ImageRef, MentionInfo, QuoteInfo, ReactionInfo,52
AttachmentInfo, FileCard, FileKind, ImageRef, MentionInfo, QuoteInfo, ReactionInfo,53
attachments, can_delete, can_edit, copy_text, files, images, mentions, message_spans, quotes,53
attachments, can_delete, can_edit, copy_text, files, images, mentions, message_spans, quotes,54
reactions,54
reactions, user_mention_inputs,55
};55
};@@ -263,6 +263,10 @@ fn mention_info(mention: &Mention) -> Option<MentionInfo> {
263
263
.and_then(|sender| sender.user_id())
264
264
.map(str::to_owned),
265
265
name,
266
id: mention.id,
267
target_id: mentioned
268
.and_then(|sender| sender.target_id())
269
.map(str::to_owned),
266
270
})
267
271
}
268
272
@@ -263,6 +263,10 @@ fn mention_info(mention: &Mention) -> Option<MentionInfo> {263
.and_then(|sender| sender.user_id())263
.and_then(|sender| sender.user_id())264
.map(str::to_owned),264
.map(str::to_owned),265
name,265
name,266
id: mention.id,267
target_id: mentioned268
.and_then(|sender| sender.target_id())269
.map(str::to_owned),266
})270
})267
}271
}268
272
@@ -16,6 +16,7 @@ pub enum Span {
16
16
},
17
17
Mention {
18
18
name: String,
19
id: Option<String>,
19
20
},
20
21
Strike(Vec<Span>),
21
22
Underline(Vec<Span>),
@@ -119,6 +120,7 @@ fn convert_element(element: ElementRef<'_>, spans: &mut Vec<Span>) {
119
120
"a" => push_link(element, spans),
120
121
"at" => spans.push(Span::Mention {
121
122
name: raw_text(element).trim().to_owned(),
123
id: element.value().attr("id").map(str::to_owned),
122
124
}),
123
125
"br" => spans.push(Span::LineBreak),
124
126
"hr" => spans.push(Span::Rule),
@@ -16,6 +16,7 @@ pub enum Span {16
},16
},17
Mention {17
Mention {18
name: String,18
name: String,19
id: Option<String>,19
},20
},20
Strike(Vec<Span>),21
Strike(Vec<Span>),21
Underline(Vec<Span>),22
Underline(Vec<Span>),@@ -119,6 +120,7 @@ fn convert_element(element: ElementRef<'_>, spans: &mut Vec<Span>) {119
"a" => push_link(element, spans),120
"a" => push_link(element, spans),120
"at" => spans.push(Span::Mention {121
"at" => spans.push(Span::Mention {121
name: raw_text(element).trim().to_owned(),122
name: raw_text(element).trim().to_owned(),123
id: element.value().attr("id").map(str::to_owned),122
}),124
}),123
"br" => spans.push(Span::LineBreak),125
"br" => spans.push(Span::LineBreak),124
"hr" => spans.push(Span::Rule),126
"hr" => spans.push(Span::Rule),@@ -3,6 +3,7 @@ use scraper::{ElementRef, Html};
3
3
use serde::{Deserialize, Serialize};
4
4
use store::MessageRecord;
5
5
6
use crate::mentions::MentionInput;
6
7
use crate::spans::{Span, html_to_spans};
7
8
8
9
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
@@ -115,6 +116,10 @@ pub struct ReactionInfo {
115
116
pub struct MentionInfo {
116
117
pub user_id: Option<String>,
117
118
pub name: String,
119
#[serde(default)]
120
pub id: Option<i64>,
121
#[serde(default)]
122
pub target_id: Option<String>,
118
123
}
119
124
120
125
pub fn attachments(record: &MessageRecord) -> Vec<AttachmentInfo> {
@@ -126,7 +131,13 @@ pub fn reactions(record: &MessageRecord) -> Vec<ReactionInfo> {
126
131
}
127
132
128
133
pub fn mentions(record: &MessageRecord) -> Vec<MentionInfo> {
129
serde_json::from_str(&record.mentions_json).unwrap_or_default()
134
let mut infos: Vec<MentionInfo> =
135
serde_json::from_str(&record.mentions_json).unwrap_or_default();
136
for (index, info) in infos.iter_mut().enumerate() {
137
info.id = info.id.or(i64::try_from(index).ok());
138
info.target_id = info.target_id.take().or_else(|| info.user_id.clone());
139
}
140
infos
130
141
}
131
142
132
143
pub fn quotes(record: &MessageRecord) -> Vec<QuoteInfo> {
@@ -302,7 +313,7 @@ fn push_plain(text: &mut String, spans: &[Span]) {
302
313
push_plain(text, children);
303
314
text.push('\n');
304
315
}
305
Span::Mention { name } => {
316
Span::Mention { name, .. } => {
306
317
text.push('@');
307
318
text.push_str(name);
308
319
}
@@ -385,7 +396,12 @@ fn leading_number(text: &str) -> Option<u32> {
385
396
386
397
/// Body spans followed by the flattened text of adaptive-card attachments.
387
398
pub fn message_spans(record: &MessageRecord) -> Vec<Span> {
399
spans_with_mentions(record, &mentions(record))
400
}
401
402
fn spans_with_mentions(record: &MessageRecord, infos: &[MentionInfo]) -> Vec<Span> {
388
403
let mut spans = html_to_spans(&record.body_html);
404
merge_split_mentions(&mut spans, infos);
389
405
for card_text in attachments(record)
390
406
.iter()
391
407
.filter(|attachment| attachment.is_card())
@@ -404,6 +420,110 @@ pub fn message_spans(record: &MessageRecord) -> Vec<Span> {
404
420
spans
405
421
}
406
422
423
pub fn user_mention_inputs(record: &MessageRecord) -> Vec<MentionInput> {
424
let infos = mentions(record);
425
let mut inputs = Vec::new();
426
collect_user_mentions(&spans_with_mentions(record, &infos), &infos, &mut inputs);
427
inputs
428
}
429
430
fn collect_user_mentions(spans: &[Span], infos: &[MentionInfo], inputs: &mut Vec<MentionInput>) {
431
for span in spans {
432
match span {
433
Span::Bold(children)
434
| Span::Italic(children)
435
| Span::Strike(children)
436
| Span::Underline(children)
437
| Span::Colored { children, .. }
438
| Span::Heading { children, .. }
439
| Span::Quote(children)
440
| Span::BlockQuote(children)
441
| Span::Link { children, .. } => collect_user_mentions(children, infos, inputs),
442
Span::List { items, .. } => items
443
.iter()
444
.for_each(|item| collect_user_mentions(item, infos, inputs)),
445
Span::Table { rows, .. } => rows
446
.iter()
447
.flatten()
448
.for_each(|cell| collect_user_mentions(cell, infos, inputs)),
449
Span::Mention { name, id } => {
450
let parsed: Option<i64> = id.as_deref().and_then(|id| id.parse().ok());
451
let user_id = infos
452
.iter()
453
.find(|info| parsed.is_some() && info.id == parsed)
454
.and_then(|info| info.user_id.as_deref());
455
if let Some(user_id) = user_id {
456
inputs.push(MentionInput::user(user_id, name));
457
}
458
}
459
_ => {}
460
}
461
}
462
}
463
464
fn merge_split_mentions(spans: &mut Vec<Span>, mentions: &[MentionInfo]) {
465
let target_of = |id: &Option<String>| -> Option<String> {
466
let parsed: i64 = id.as_deref()?.parse().ok()?;
467
mentions
468
.iter()
469
.find(|info| info.id == Some(parsed))?
470
.target_id
471
.clone()
472
};
473
let mut merged: Vec<Span> = Vec::with_capacity(spans.len());
474
for mut span in std::mem::take(spans) {
475
match &mut span {
476
Span::Bold(children)
477
| Span::Italic(children)
478
| Span::Strike(children)
479
| Span::Underline(children)
480
| Span::Colored { children, .. }
481
| Span::Heading { children, .. }
482
| Span::Quote(children)
483
| Span::BlockQuote(children)
484
| Span::Link { children, .. } => merge_split_mentions(children, mentions),
485
Span::List { items, .. } => items
486
.iter_mut()
487
.for_each(|item| merge_split_mentions(item, mentions)),
488
Span::Table { rows, .. } => rows
489
.iter_mut()
490
.flatten()
491
.for_each(|cell| merge_split_mentions(cell, mentions)),
492
Span::Mention { name, id } => {
493
let continues = match merged.as_slice() {
494
[
495
..,
496
Span::Mention {
497
id: previous_id, ..
498
},
499
Span::Text(gap),
500
] => {
501
gap.trim().is_empty()
502
&& target_of(id).is_some()
503
&& target_of(previous_id) == target_of(id)
504
}
505
_ => false,
506
};
507
if continues {
508
merged.pop();
509
if let Some(Span::Mention {
510
name: previous_name,
511
..
512
}) = merged.last_mut()
513
{
514
previous_name.push(' ');
515
previous_name.push_str(name);
516
}
517
continue;
518
}
519
}
520
_ => {}
521
}
522
merged.push(span);
523
}
524
*spans = merged;
525
}
526
407
527
#[cfg(test)]
408
528
mod tests {
409
529
use chrono::Utc;
@@ -602,4 +722,107 @@ mod tests {
602
722
let stored = record("", &serde_json::to_string(&[info]).unwrap());
603
723
assert_eq!(quotes(&stored).len(), 1);
604
724
}
725
726
fn with_mentions(body_html: &str, mentions_json: &str) -> MessageRecord {
727
let mut stored = record(body_html, "[]");
728
stored.mentions_json = mentions_json.to_owned();
729
stored
730
}
731
732
fn mention_names(spans: &[Span]) -> Vec<&str> {
733
spans
734
.iter()
735
.filter_map(|span| match span {
736
Span::Mention { name, .. } => Some(name.as_str()),
737
_ => None,
738
})
739
.collect()
740
}
741
742
#[test]
743
fn a_tag_mention_split_per_word_merges_into_one() {
744
let json = r#"[
745
{"user_id":null,"name":"Tip","id":0,"target_id":"T1"},
746
{"user_id":null,"name":"of","id":1,"target_id":"T1"},
747
{"user_id":null,"name":"the","id":2,"target_id":"T1"},
748
{"user_id":null,"name":"day","id":3,"target_id":"T1"}
749
]"#;
750
let html = r#"<p>Hey <at id="0">Tip</at> <at id="1">of</at> <at id="2">the</at> <at id="3">day</at>!</p>"#;
751
let spans = message_spans(&with_mentions(html, json));
752
assert_eq!(mention_names(&spans), vec!["Tip of the day"]);
753
assert_eq!(
754
copy_text(&with_mentions(html, json)),
755
"Hey @Tip of the day!"
756
);
757
}
758
759
#[test]
760
fn a_two_word_user_name_merges_but_different_users_stay_apart() {
761
let json = r#"[
762
{"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
763
{"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"},
764
{"user_id":"U2","name":"Bob","id":2,"target_id":"U2"}
765
]"#;
766
let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Bob</at>"#;
767
let spans = message_spans(&with_mentions(html, json));
768
assert_eq!(mention_names(&spans), vec!["Ada Lovelace", "Bob"]);
769
}
770
771
#[test]
772
fn different_users_next_to_each_other_stay_two_mentions() {
773
let json = r#"[
774
{"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
775
{"user_id":"U2","name":"Bob","id":1,"target_id":"U2"}
776
]"#;
777
let html = r#"<at id="0">Ada</at> <at id="1">Bob</at>"#;
778
let spans = message_spans(&with_mentions(html, json));
779
assert_eq!(mention_names(&spans), vec!["Ada", "Bob"]);
780
}
781
782
#[test]
783
fn nested_split_mentions_merge() {
784
let json = r#"[
785
{"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
786
{"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"}
787
]"#;
788
let html = r#"<b><at id="0">Ada</at> <at id="1">Lovelace</at></b>"#;
789
let spans = message_spans(&with_mentions(html, json));
790
let [Span::Bold(children)] = spans.as_slice() else {
791
panic!("bold expected: {spans:?}")
792
};
793
assert_eq!(mention_names(children), vec!["Ada Lovelace"]);
794
}
795
796
#[test]
797
fn old_mention_json_without_ids_merges_users_by_position() {
798
let json = r#"[{"user_id":"U1","name":"Ada"},{"user_id":"U1","name":"Lovelace"},{"user_id":null,"name":"Tip"},{"user_id":null,"name":"day"}]"#;
799
let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Tip</at> <at id="3">day</at>"#;
800
let stored = with_mentions(html, json);
801
let parsed = mentions(&stored);
802
assert_eq!(
803
(parsed[1].id, parsed[1].target_id.as_deref()),
804
(Some(1), Some("U1"))
805
);
806
assert_eq!(
807
mention_names(&message_spans(&stored)),
808
vec!["Ada Lovelace", "Tip", "day"]
809
);
810
}
811
812
#[test]
813
fn edit_mentions_follow_the_merged_names() {
814
let json = r#"[
815
{"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
816
{"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"},
817
{"user_id":"U2","name":"Bob","id":2,"target_id":"U2"}
818
]"#;
819
let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> and <at id="2">Bob</at>"#;
820
assert_eq!(
821
user_mention_inputs(&with_mentions(html, json)),
822
vec![
823
MentionInput::user("U1", "Ada Lovelace"),
824
MentionInput::user("U2", "Bob"),
825
]
826
);
827
}
605
828
}
@@ -3,6 +3,7 @@ use scraper::{ElementRef, Html};3
use serde::{Deserialize, Serialize};3
use serde::{Deserialize, Serialize};4
use store::MessageRecord;4
use store::MessageRecord;5
5
6
use crate::mentions::MentionInput;6
use crate::spans::{Span, html_to_spans};7
use crate::spans::{Span, html_to_spans};7
8
8
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";9
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";@@ -115,6 +116,10 @@ pub struct ReactionInfo {115
pub struct MentionInfo {116
pub struct MentionInfo {116
pub user_id: Option<String>,117
pub user_id: Option<String>,117
pub name: String,118
pub name: String,119
#[serde(default)]120
pub id: Option<i64>,121
#[serde(default)]122
pub target_id: Option<String>,118
}123
}119
124
120
pub fn attachments(record: &MessageRecord) -> Vec<AttachmentInfo> {125
pub fn attachments(record: &MessageRecord) -> Vec<AttachmentInfo> {@@ -126,7 +131,13 @@ pub fn reactions(record: &MessageRecord) -> Vec<ReactionInfo> {126
}131
}127
132
128
pub fn mentions(record: &MessageRecord) -> Vec<MentionInfo> {133
pub fn mentions(record: &MessageRecord) -> Vec<MentionInfo> {129
serde_json::from_str(&record.mentions_json).unwrap_or_default()134
let mut infos: Vec<MentionInfo> =135
serde_json::from_str(&record.mentions_json).unwrap_or_default();136
for (index, info) in infos.iter_mut().enumerate() {137
info.id = info.id.or(i64::try_from(index).ok());138
info.target_id = info.target_id.take().or_else(|| info.user_id.clone());139
}140
infos130
}141
}131
142
132
pub fn quotes(record: &MessageRecord) -> Vec<QuoteInfo> {143
pub fn quotes(record: &MessageRecord) -> Vec<QuoteInfo> {@@ -302,7 +313,7 @@ fn push_plain(text: &mut String, spans: &[Span]) {302
push_plain(text, children);313
push_plain(text, children);303
text.push('\n');314
text.push('\n');304
}315
}305
Span::Mention { name } => {316
Span::Mention { name, .. } => {306
text.push('@');317
text.push('@');307
text.push_str(name);318
text.push_str(name);308
}319
}@@ -385,7 +396,12 @@ fn leading_number(text: &str) -> Option<u32> {385
396
386
/// Body spans followed by the flattened text of adaptive-card attachments.397
/// Body spans followed by the flattened text of adaptive-card attachments.387
pub fn message_spans(record: &MessageRecord) -> Vec<Span> {398
pub fn message_spans(record: &MessageRecord) -> Vec<Span> {399
spans_with_mentions(record, &mentions(record))400
}401
402
fn spans_with_mentions(record: &MessageRecord, infos: &[MentionInfo]) -> Vec<Span> {388
let mut spans = html_to_spans(&record.body_html);403
let mut spans = html_to_spans(&record.body_html);404
merge_split_mentions(&mut spans, infos);389
for card_text in attachments(record)405
for card_text in attachments(record)390
.iter()406
.iter()391
.filter(|attachment| attachment.is_card())407
.filter(|attachment| attachment.is_card())@@ -404,6 +420,110 @@ pub fn message_spans(record: &MessageRecord) -> Vec<Span> {404
spans420
spans405
}421
}406
422
423
pub fn user_mention_inputs(record: &MessageRecord) -> Vec<MentionInput> {424
let infos = mentions(record);425
let mut inputs = Vec::new();426
collect_user_mentions(&spans_with_mentions(record, &infos), &infos, &mut inputs);427
inputs428
}429
430
fn collect_user_mentions(spans: &[Span], infos: &[MentionInfo], inputs: &mut Vec<MentionInput>) {431
for span in spans {432
match span {433
Span::Bold(children)434
| Span::Italic(children)435
| Span::Strike(children)436
| Span::Underline(children)437
| Span::Colored { children, .. }438
| Span::Heading { children, .. }439
| Span::Quote(children)440
| Span::BlockQuote(children)441
| Span::Link { children, .. } => collect_user_mentions(children, infos, inputs),442
Span::List { items, .. } => items443
.iter()444
.for_each(|item| collect_user_mentions(item, infos, inputs)),445
Span::Table { rows, .. } => rows446
.iter()447
.flatten()448
.for_each(|cell| collect_user_mentions(cell, infos, inputs)),449
Span::Mention { name, id } => {450
let parsed: Option<i64> = id.as_deref().and_then(|id| id.parse().ok());451
let user_id = infos452
.iter()453
.find(|info| parsed.is_some() && info.id == parsed)454
.and_then(|info| info.user_id.as_deref());455
if let Some(user_id) = user_id {456
inputs.push(MentionInput::user(user_id, name));457
}458
}459
_ => {}460
}461
}462
}463
464
fn merge_split_mentions(spans: &mut Vec<Span>, mentions: &[MentionInfo]) {465
let target_of = |id: &Option<String>| -> Option<String> {466
let parsed: i64 = id.as_deref()?.parse().ok()?;467
mentions468
.iter()469
.find(|info| info.id == Some(parsed))?470
.target_id471
.clone()472
};473
let mut merged: Vec<Span> = Vec::with_capacity(spans.len());474
for mut span in std::mem::take(spans) {475
match &mut span {476
Span::Bold(children)477
| Span::Italic(children)478
| Span::Strike(children)479
| Span::Underline(children)480
| Span::Colored { children, .. }481
| Span::Heading { children, .. }482
| Span::Quote(children)483
| Span::BlockQuote(children)484
| Span::Link { children, .. } => merge_split_mentions(children, mentions),485
Span::List { items, .. } => items486
.iter_mut()487
.for_each(|item| merge_split_mentions(item, mentions)),488
Span::Table { rows, .. } => rows489
.iter_mut()490
.flatten()491
.for_each(|cell| merge_split_mentions(cell, mentions)),492
Span::Mention { name, id } => {493
let continues = match merged.as_slice() {494
[495
..,496
Span::Mention {497
id: previous_id, ..498
},499
Span::Text(gap),500
] => {501
gap.trim().is_empty()502
&& target_of(id).is_some()503
&& target_of(previous_id) == target_of(id)504
}505
_ => false,506
};507
if continues {508
merged.pop();509
if let Some(Span::Mention {510
name: previous_name,511
..512
}) = merged.last_mut()513
{514
previous_name.push(' ');515
previous_name.push_str(name);516
}517
continue;518
}519
}520
_ => {}521
}522
merged.push(span);523
}524
*spans = merged;525
}526
407
#[cfg(test)]527
#[cfg(test)]408
mod tests {528
mod tests {409
use chrono::Utc;529
use chrono::Utc;@@ -602,4 +722,107 @@ mod tests {602
let stored = record("", &serde_json::to_string(&[info]).unwrap());722
let stored = record("", &serde_json::to_string(&[info]).unwrap());603
assert_eq!(quotes(&stored).len(), 1);723
assert_eq!(quotes(&stored).len(), 1);604
}724
}725
726
fn with_mentions(body_html: &str, mentions_json: &str) -> MessageRecord {727
let mut stored = record(body_html, "[]");728
stored.mentions_json = mentions_json.to_owned();729
stored730
}731
732
fn mention_names(spans: &[Span]) -> Vec<&str> {733
spans734
.iter()735
.filter_map(|span| match span {736
Span::Mention { name, .. } => Some(name.as_str()),737
_ => None,738
})739
.collect()740
}741
742
#[test]743
fn a_tag_mention_split_per_word_merges_into_one() {744
let json = r#"[745
{"user_id":null,"name":"Tip","id":0,"target_id":"T1"},746
{"user_id":null,"name":"of","id":1,"target_id":"T1"},747
{"user_id":null,"name":"the","id":2,"target_id":"T1"},748
{"user_id":null,"name":"day","id":3,"target_id":"T1"}749
]"#;750
let html = r#"<p>Hey <at id="0">Tip</at> <at id="1">of</at> <at id="2">the</at> <at id="3">day</at>!</p>"#;751
let spans = message_spans(&with_mentions(html, json));752
assert_eq!(mention_names(&spans), vec!["Tip of the day"]);753
assert_eq!(754
copy_text(&with_mentions(html, json)),755
"Hey @Tip of the day!"756
);757
}758
759
#[test]760
fn a_two_word_user_name_merges_but_different_users_stay_apart() {761
let json = r#"[762
{"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},763
{"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"},764
{"user_id":"U2","name":"Bob","id":2,"target_id":"U2"}765
]"#;766
let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Bob</at>"#;767
let spans = message_spans(&with_mentions(html, json));768
assert_eq!(mention_names(&spans), vec!["Ada Lovelace", "Bob"]);769
}770
771
#[test]772
fn different_users_next_to_each_other_stay_two_mentions() {773
let json = r#"[774
{"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},775
{"user_id":"U2","name":"Bob","id":1,"target_id":"U2"}776
]"#;777
let html = r#"<at id="0">Ada</at> <at id="1">Bob</at>"#;778
let spans = message_spans(&with_mentions(html, json));779
assert_eq!(mention_names(&spans), vec!["Ada", "Bob"]);780
}781
782
#[test]783
fn nested_split_mentions_merge() {784
let json = r#"[785
{"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},786
{"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"}787
]"#;788
let html = r#"<b><at id="0">Ada</at> <at id="1">Lovelace</at></b>"#;789
let spans = message_spans(&with_mentions(html, json));790
let [Span::Bold(children)] = spans.as_slice() else {791
panic!("bold expected: {spans:?}")792
};793
assert_eq!(mention_names(children), vec!["Ada Lovelace"]);794
}795
796
#[test]797
fn old_mention_json_without_ids_merges_users_by_position() {798
let json = r#"[{"user_id":"U1","name":"Ada"},{"user_id":"U1","name":"Lovelace"},{"user_id":null,"name":"Tip"},{"user_id":null,"name":"day"}]"#;799
let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Tip</at> <at id="3">day</at>"#;800
let stored = with_mentions(html, json);801
let parsed = mentions(&stored);802
assert_eq!(803
(parsed[1].id, parsed[1].target_id.as_deref()),804
(Some(1), Some("U1"))805
);806
assert_eq!(807
mention_names(&message_spans(&stored)),808
vec!["Ada Lovelace", "Tip", "day"]809
);810
}811
812
#[test]813
fn edit_mentions_follow_the_merged_names() {814
let json = r#"[815
{"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},816
{"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"},817
{"user_id":"U2","name":"Bob","id":2,"target_id":"U2"}818
]"#;819
let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> and <at id="2">Bob</at>"#;820
assert_eq!(821
user_mention_inputs(&with_mentions(html, json)),822
vec![823
MentionInput::user("U1", "Ada Lovelace"),824
MentionInput::user("U2", "Bob"),825
]826
);827
}605
}828
}@@ -49,7 +49,8 @@ fn mention_uses_the_visible_name() {
49
49
html_to_spans(r#"<p><at id="0">Ada Example</at> please look</p>"#),
50
50
vec![
51
51
Span::Mention {
52
name: "Ada Example".to_owned()
52
name: "Ada Example".to_owned(),
53
id: Some("0".to_owned())
53
54
},
54
55
text(" please look")
55
56
]
@@ -49,7 +49,8 @@ fn mention_uses_the_visible_name() {49
html_to_spans(r#"<p><at id="0">Ada Example</at> please look</p>"#),49
html_to_spans(r#"<p><at id="0">Ada Example</at> please look</p>"#),50
vec![50
vec![51
Span::Mention {51
Span::Mention {52
name: "Ada Example".to_owned()52
name: "Ada Example".to_owned(),53
id: Some("0".to_owned())53
},54
},54
text(" please look")55
text(" please look")55
]56
]@@ -32,16 +32,25 @@ pub struct Identity {
32
32
pub struct Sender {
33
33
pub user: Option<Identity>,
34
34
pub application: Option<Identity>,
35
pub tag: Option<Identity>,
36
pub conversation: Option<Identity>,
35
37
}
36
38
37
39
impl Sender {
38
40
pub fn display_name(&self) -> Option<&str> {
39
[&self.user, &self.application]
41
[&self.user, &self.application, &self.tag, &self.conversation]
40
42
.into_iter()
41
43
.flatten()
42
44
.find_map(|identity| identity.display_name.as_deref())
43
45
}
44
46
47
pub fn target_id(&self) -> Option<&str> {
48
[&self.user, &self.application, &self.tag, &self.conversation]
49
.into_iter()
50
.flatten()
51
.find_map(|identity| identity.id.as_deref())
52
}
53
45
54
pub fn user_id(&self) -> Option<&str> {
46
55
self.user.as_ref().and_then(|user| user.id.as_deref())
47
56
}
@@ -32,16 +32,25 @@ pub struct Identity {32
pub struct Sender {32
pub struct Sender {33
pub user: Option<Identity>,33
pub user: Option<Identity>,34
pub application: Option<Identity>,34
pub application: Option<Identity>,35
pub tag: Option<Identity>,36
pub conversation: Option<Identity>,35
}37
}36
38
37
impl Sender {39
impl Sender {38
pub fn display_name(&self) -> Option<&str> {40
pub fn display_name(&self) -> Option<&str> {39
[&self.user, &self.application]41
[&self.user, &self.application, &self.tag, &self.conversation]40
.into_iter()42
.into_iter()41
.flatten()43
.flatten()42
.find_map(|identity| identity.display_name.as_deref())44
.find_map(|identity| identity.display_name.as_deref())43
}45
}44
46
47
pub fn target_id(&self) -> Option<&str> {48
[&self.user, &self.application, &self.tag, &self.conversation]49
.into_iter()50
.flatten()51
.find_map(|identity| identity.id.as_deref())52
}53
45
pub fn user_id(&self) -> Option<&str> {54
pub fn user_id(&self) -> Option<&str> {46
self.user.as_ref().and_then(|user| user.id.as_deref())55
self.user.as_ref().and_then(|user| user.id.as_deref())47
}56
}@@ -89,3 +89,15 @@ fn parses_channel_thread_with_replies() {
89
89
Some("1800000000001")
90
90
);
91
91
}
92
93
#[test]
94
fn a_tag_mention_exposes_its_target_id_and_name() {
95
let message: Message = serde_json::from_str(
96
r#"{"id":"1","mentions":[{"id":0,"mentionText":"Tip","mentioned":{"tag":{"id":"T1","displayName":"Tip of the day"}}}]}"#,
97
)
98
.unwrap();
99
let mentioned = message.mentions[0].mentioned.as_ref().unwrap();
100
assert_eq!(mentioned.target_id(), Some("T1"));
101
assert_eq!(mentioned.display_name(), Some("Tip of the day"));
102
assert_eq!(mentioned.user_id(), None);
103
}
@@ -89,3 +89,15 @@ fn parses_channel_thread_with_replies() {89
Some("1800000000001")89
Some("1800000000001")90
);90
);91
}91
}92
93
#[test]94
fn a_tag_mention_exposes_its_target_id_and_name() {95
let message: Message = serde_json::from_str(96
r#"{"id":"1","mentions":[{"id":0,"mentionText":"Tip","mentioned":{"tag":{"id":"T1","displayName":"Tip of the day"}}}]}"#,97
)98
.unwrap();99
let mentioned = message.mentions[0].mentioned.as_ref().unwrap();100
assert_eq!(mentioned.target_id(), Some("T1"));101
assert_eq!(mentioned.display_name(), Some("Tip of the day"));102
assert_eq!(mentioned.user_id(), None);103
}