BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / rows.rs

rows.rs

rows.rs 77.8 KiB Download Raw
1use std::collections::{BTreeMap, HashMap};
2use std::ops::Range;
3use std::sync::Arc;
4
5use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6use gpui_kit::Image;
7use store::{MessageImportance, MessageRecord};
8use teams_core::roster_event::{RosterEvent, roster_event};
9use teams_core::{
10 AnnouncementBanner, attachments,
11 JumboEmoji, jumbo_emoji,
12 AdaptiveCard, CallEvent, CallPhase, Draft, FileCard, ForwardHeader, ForwardInfo,
13 ImageRef, LinkPreview, forwards,
14 ReactionInfo, Span, adaptive_cards, call_event, card_texts, files,
15 forwarded_texts, images, is_forwarded, link_preview, linked_message_spans_with, meeting_link_in_html, message_spans, quotes,
16 reactions, readable_text, translated_spans,
17};
18
19pub use crate::call_rows::{
20 CallCard, CallIcon, CallNotice, CallParticipant, MeetingInfo, MeetingSlot, RecapCard,
21 RecordingCard,
22};
23use crate::call_rows::{CallClock, CallNames, CallSource, CallTimeline, call_card, roster_card};
24use crate::card_state::CardOverride;
25use crate::format;
26use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
27use crate::render::blocks::{Inline, strip_image_placeholders};
28use crate::render::{Block, layout_blocks};
29use crate::translation::{TranslationContext, TranslationLine};
30
31const POST_VISIBLE_REPLIES: usize = 3;
32
33pub const LOAD_OLDER_KEY: &str = "load-older";
34pub const LOAD_NEWER_KEY: &str = "load-newer";
35const UNKNOWN_AUTHOR: &str = "Unknown";
36const DELETED_TEXT: &str = "Message deleted";
37const SERIES_GAP_MINUTES: i64 = 5;
38const CORNER_RADIUS: f32 = 14.;
39const CORNER_SERIES: f32 = 4.;
40
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct ReactionChip {
43 pub reaction_type: String,
44 pub label: String,
45 pub click_glyph: String,
46 pub count: usize,
47 pub mine: bool,
48 pub reactors: Vec<Reactor>,
49}
50
51impl ReactionChip {
52 pub fn glyph(&self) -> String {
53 reaction_glyph(&self.reaction_type)
54 }
55
56 pub fn custom_emoji_image(&self) -> Option<ImageRef> {
57 custom_emoji_image(&self.reaction_type)
58 }
59}
60
61/// Text for places without images: the org emoji's name instead of its raw key.
62pub fn reaction_text(reaction_type: &str) -> String {
63 match chatsvc::custom_emoji(reaction_type) {
64 Some(emoji) => format!(":{}:", emoji.name),
65 None => reaction_glyph(reaction_type),
66 }
67}
68
69pub fn custom_emoji_image(reaction_type: &str) -> Option<ImageRef> {
70 let emoji = chatsvc::custom_emoji(reaction_type)?;
71 Some(ImageRef {
72 id: emoji.object_id.to_owned(),
73 url: emoji.image_url(),
74 width: None,
75 height: None,
76 alt: Some(emoji.name.to_owned()),
77 })
78}
79
80#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
81pub struct Series {
82 pub has_prev: bool,
83 pub has_next: bool,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq)]
87pub struct Corners {
88 pub top_left: f32,
89 pub top_right: f32,
90 pub bottom_right: f32,
91 pub bottom_left: f32,
92}
93
94pub fn bubble_corners(own: bool, series: Series) -> Corners {
95 let joined = |joined: bool| if joined { CORNER_SERIES } else { CORNER_RADIUS };
96 if own {
97 Corners {
98 top_left: CORNER_RADIUS,
99 top_right: joined(series.has_prev),
100 bottom_right: joined(series.has_next),
101 bottom_left: CORNER_RADIUS,
102 }
103 } else {
104 Corners {
105 top_left: joined(series.has_prev),
106 top_right: CORNER_RADIUS,
107 bottom_right: CORNER_RADIUS,
108 bottom_left: joined(series.has_next),
109 }
110 }
111}
112
113#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
114pub enum Receipt {
115 #[default]
116 Hidden,
117 Sent,
118 Read,
119 ReadLive,
120}
121
122pub fn receipt_label(state: &teams_core::ReceiptState) -> Option<String> {
123 match state {
124 teams_core::ReceiptState::Sent => Some("Sent".to_owned()),
125 teams_core::ReceiptState::Read { readers, total_others } if *total_others > 1 => {
126 if readers.len() >= *total_others {
127 Some("Seen by everyone".to_owned())
128 } else {
129 let names: Vec<&str> = readers.iter().map(|reader| reader.name.as_str()).collect();
130 Some(format!("Seen by {}", names.join(", ")))
131 }
132 }
133 teams_core::ReceiptState::Read { .. } => Some("Seen".to_owned()),
134 teams_core::ReceiptState::Unknown => None,
135 }
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum ScheduledState {
140 Waiting,
141 DeliveryFailed,
142 ChangeFailed,
143}
144
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub enum Delivery {
147 Delivered,
148 Sending,
149 Failed(String),
150 Scheduled(ScheduledState),
151}
152
153/// An image of a message that is still being sent, shown from its local bytes.
154#[derive(Debug, Clone, PartialEq)]
155pub struct LocalImage {
156 pub image: Arc<Image>,
157 pub size: Option<(u32, u32)>,
158}
159
160#[derive(Debug, Clone, PartialEq)]
161pub struct MessageRow {
162 pub key: String,
163 pub conversation_id: String,
164 pub author: String,
165 pub sender_id: Option<String>,
166 pub application_id: Option<String>,
167 pub created_at: DateTime<Utc>,
168 pub series: Series,
169 pub time: String,
170 pub day_header: Option<String>,
171 pub blocks: Vec<Block>,
172 pub jumbo: Option<Vec<JumboEmoji>>,
173 pub edited: bool,
174 pub deleted: bool,
175 pub reactions: Vec<ReactionChip>,
176 pub images: Vec<ImageRef>,
177 pub local_images: Vec<LocalImage>,
178 pub files: Vec<FileCard>,
179 pub link_preview: Option<LinkPreview>,
180 pub meeting_link: Option<String>,
181 pub adaptive_cards: Vec<AdaptiveCard>,
182 pub subject: Option<String>,
183 pub banner: Option<AnnouncementBanner>,
184 pub importance: MessageImportance,
185 pub new_marker: bool,
186 pub reply_root: Option<String>,
187 pub delivery: Delivery,
188 pub own: bool,
189 pub receipt: Receipt,
190 pub receipt_label: Option<String>,
191 pub forwarded: bool,
192 pub translation: Option<TranslationLine>,
193 pub call: Option<CallCard>,
194}
195
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct StartInfo {
198 pub title: String,
199 pub user_id: Option<String>,
200 pub avatar_name: String,
201 pub notes: bool,
202}
203
204pub const START_KEY: &str = "conversation-start";
205
206#[derive(Debug, Clone, PartialEq)]
207pub enum Row {
208 LoadOlder,
209 LoadNewer,
210 Start(StartInfo),
211 Skeleton(Skeleton),
212 Message(Box<MessageRow>),
213 Post(Box<PostRow>),
214}
215
216#[derive(Debug, Clone, Copy, PartialEq)]
217pub struct Skeleton {
218 pub key: &'static str,
219 pub own: bool,
220 pub width_ratio: f32,
221 pub lines: u8,
222}
223
224const SKELETON_PLACEHOLDERS: [Skeleton; 4] = [
225 Skeleton {
226 key: "skeleton-0",
227 own: false,
228 width_ratio: 0.42,
229 lines: 1,
230 },
231 Skeleton {
232 key: "skeleton-1",
233 own: true,
234 width_ratio: 0.3,
235 lines: 1,
236 },
237 Skeleton {
238 key: "skeleton-2",
239 own: true,
240 width_ratio: 0.48,
241 lines: 2,
242 },
243 Skeleton {
244 key: "skeleton-3",
245 own: false,
246 width_ratio: 0.26,
247 lines: 1,
248 },
249];
250
251pub fn placeholder_rows() -> Vec<Row> {
252 SKELETON_PLACEHOLDERS
253 .into_iter()
254 .map(Row::Skeleton)
255 .collect()
256}
257
258fn sender_key(row: &MessageRow) -> &str {
259 row.sender_id.as_deref().unwrap_or(&row.author)
260}
261
262fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool {
263 previous.call.is_none()
264 && next.call.is_none()
265 && next.day_header.is_none()
266 && !next.new_marker
267 && sender_key(previous) == sender_key(next)
268 && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES)
269 && next.created_at >= previous.created_at
270}
271
272pub fn assign_series(rows: &mut [Row]) {
273 let mut previous: Option<usize> = None;
274 for index in 0..rows.len() {
275 let Row::Message(_) = &rows[index] else {
276 previous = None;
277 continue;
278 };
279 if let Some(before) = previous {
280 let joined = match (&rows[before], &rows[index]) {
281 (Row::Message(a), Row::Message(b)) => continues_series(a, b),
282 _ => false,
283 };
284 if joined {
285 if let Row::Message(a) = &mut rows[before] {
286 a.series.has_next = true;
287 }
288 if let Row::Message(b) = &mut rows[index] {
289 b.series.has_prev = true;
290 }
291 }
292 }
293 previous = Some(index);
294 }
295}
296
297impl Row {
298 pub fn key(&self) -> &str {
299 match self {
300 Row::LoadOlder => LOAD_OLDER_KEY,
301 Row::LoadNewer => LOAD_NEWER_KEY,
302 Row::Start(_) => START_KEY,
303 Row::Skeleton(skeleton) => skeleton.key,
304 Row::Message(message) => &message.key,
305 Row::Post(post) => &post.root.key,
306 }
307 }
308
309 pub fn messages(&self) -> Box<dyn Iterator<Item = &MessageRow> + '_> {
310 match self {
311 Row::Message(message) => Box::new(std::iter::once(message.as_ref())),
312 Row::Post(post) => Box::new(post.messages()),
313 Row::LoadOlder | Row::LoadNewer | Row::Start(_) | Row::Skeleton(_) => {
314 Box::new(std::iter::empty())
315 }
316 }
317 }
318}
319
320#[derive(Debug, Clone, PartialEq)]
321pub struct PostRow {
322 pub root: MessageRow,
323 pub replies: Vec<MessageRow>,
324 pub hidden_reply_count: usize,
325 pub hidden_repliers: Vec<String>,
326 pub is_new: bool,
327}
328
329impl PostRow {
330 pub fn local(root: MessageRow) -> Self {
331 PostRow {
332 root,
333 replies: Vec::new(),
334 hidden_reply_count: 0,
335 hidden_repliers: Vec::new(),
336 is_new: false,
337 }
338 }
339
340 pub fn messages(&self) -> impl Iterator<Item = &MessageRow> {
341 std::iter::once(&self.root).chain(&self.replies)
342 }
343
344 /// Teams marks a post "New" when someone else posted it after the channel's read horizon.
345 pub fn mark_new_after(&mut self, read_until: DateTime<Utc>) {
346 self.is_new = !self.root.own && self.root.created_at > read_until;
347 }
348
349 pub fn hidden_replies_label(&self) -> Option<String> {
350 (self.hidden_reply_count > 0)
351 .then(|| replies_label(self.hidden_reply_count, &self.hidden_repliers))
352 }
353}
354
355fn first_name(name: &str) -> &str {
356 name.split_whitespace().next().unwrap_or(name)
357}
358
359pub fn replies_label(count: usize, repliers: &[String]) -> String {
360 let noun = if count == 1 { "reply" } else { "replies" };
361 let mut names: Vec<&str> = Vec::new();
362 for name in repliers.iter().map(|name| first_name(name)) {
363 if !names.contains(&name) {
364 names.push(name);
365 }
366 }
367 let people = match names.as_slice() {
368 [] => return format!("{count} {noun}"),
369 [only] => (*only).to_owned(),
370 [first, second] => format!("{first} and {second}"),
371 [first, second, third] => format!("{first}, {second} and {third}"),
372 [first, second, rest @ ..] => format!("{first}, {second} and {} others", rest.len()),
373 };
374 format!("{count} {noun} from {people}")
375}
376
377#[derive(Debug, Clone, PartialEq, Eq)]
378pub struct Thread {
379 pub root_id: String,
380 pub reply_ids: Vec<String>,
381}
382
383pub fn clock_label(time: DateTime<Utc>, offset: FixedOffset) -> String {
384 time.with_timezone(&offset)
385 .format(app_base::format::clock_format())
386 .to_string()
387}
388
389pub fn reaction_label(reaction_type: &str) -> String {
390 match reaction_type {
391 "like" => "\u{1F44D}".to_owned(),
392 "heart" => "\u{2764}".to_owned(),
393 "laugh" => "\u{1F606}".to_owned(),
394 "surprised" => "\u{1F62E}".to_owned(),
395 "sad" => "\u{1F641}".to_owned(),
396 "angry" => "\u{1F620}".to_owned(),
397 other => other.to_owned(),
398 }
399}
400
401pub fn reaction_glyph(reaction_type: &str) -> String {
402 let label = reaction_label(reaction_type);
403 let glyph = if label == reaction_type {
404 chatsvc::reaction_glyph_for_key(reaction_type).unwrap_or(label)
405 } else {
406 label
407 };
408 glyph.trim_end_matches('\u{FE0F}').to_owned()
409}
410
411fn same_reaction(left: &str, right: &str) -> bool {
412 crate::emoticons::without_tone(left) == crate::emoticons::without_tone(right)
413}
414
415/// Graph rejects the legacy names ("Unicode 'like' in the payload is not supported").
416pub fn api_reaction(glyph: &str) -> String {
417 match glyph {
418 "\u{2764}" => "\u{2764}\u{FE0F}".to_owned(),
419 other => other.to_owned(),
420 }
421}
422
423/// The reaction type Teams uses for a glyph: the legacy name for the six classic ones.
424pub fn reaction_type_for(glyph: &str) -> String {
425 let bare = glyph.trim_end_matches('\u{FE0F}');
426 ["like", "heart", "laugh", "surprised", "sad", "angry"]
427 .into_iter()
428 .find(|name| reaction_label(name) == bare)
429 .map_or_else(|| bare.to_owned(), str::to_owned)
430}
431
432const MAX_TONE_VARIANTS: usize = 3;
433
434pub type PendingReactions = HashMap<String, Vec<(String, bool)>>;
435
436fn is_own_reaction(reaction: &ReactionInfo, wanted: &str, my_user_id: Option<&str>) -> bool {
437 my_user_id.is_some()
438 && reaction.user_id.as_deref() == my_user_id
439 && same_reaction(&reaction_glyph(&reaction.reaction_type), wanted)
440}
441
442/// The glyph of the own reaction that matches `glyph` regardless of skin tone.
443pub fn own_reaction_glyph(
444 reactions: &[ReactionInfo],
445 glyph: &str,
446 my_user_id: Option<&str>,
447) -> Option<String> {
448 let wanted = reaction_glyph(glyph);
449 reactions
450 .iter()
451 .find(|reaction| is_own_reaction(reaction, &wanted, my_user_id))
452 .map(|reaction| reaction_glyph(&reaction.reaction_type))
453}
454
455pub fn has_own_reaction(reactions: &[ReactionInfo], glyph: &str, my_user_id: Option<&str>) -> bool {
456 let wanted = reaction_glyph(glyph);
457 reactions
458 .iter()
459 .any(|reaction| is_own_reaction(reaction, &wanted, my_user_id))
460}
461
462pub fn set_own_reaction(
463 reactions: &mut Vec<ReactionInfo>,
464 glyph: &str,
465 my_user_id: Option<&str>,
466 present: bool,
467 now: DateTime<Utc>,
468) {
469 let wanted = reaction_glyph(glyph);
470 if !present {
471 reactions.retain(|reaction| !is_own_reaction(reaction, &wanted, my_user_id));
472 } else if !has_own_reaction(reactions, glyph, my_user_id) {
473 reactions.push(ReactionInfo {
474 reaction_type: reaction_type_for(glyph),
475 user_id: my_user_id.map(str::to_owned),
476 user_name: Some("You".to_owned()),
477 created_at: Some(now),
478 });
479 }
480}
481
482pub fn apply_pending_reactions(
483 reactions: &mut Vec<ReactionInfo>,
484 pending: Option<&Vec<(String, bool)>>,
485 my_user_id: Option<&str>,
486 now: DateTime<Utc>,
487) {
488 for (glyph, present) in pending.into_iter().flatten() {
489 set_own_reaction(reactions, glyph, my_user_id, *present, now);
490 }
491}
492
493pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> {
494 let my_user_id = context.my_user_id.as_deref();
495 let mut chips: Vec<ReactionChip> = Vec::new();
496 let mut variants: Vec<Vec<String>> = Vec::new();
497 for reaction in reactions {
498 let glyph = reaction_glyph(&reaction.reaction_type);
499 let position = match chips
500 .iter()
501 .position(|chip| same_reaction(&chip.glyph(), &glyph))
502 {
503 Some(position) => position,
504 None => {
505 chips.push(ReactionChip {
506 reaction_type: reaction.reaction_type.clone(),
507 label: String::new(),
508 click_glyph: crate::emoticons::with_tone(&glyph, context.skin_tone),
509 count: 0,
510 mine: false,
511 reactors: Vec::new(),
512 });
513 variants.push(Vec::new());
514 chips.len() - 1
515 }
516 };
517 let label = glyph;
518 let shown = &mut variants[position];
519 if shown.len() < MAX_TONE_VARIANTS && !shown.contains(&label) {
520 shown.push(label);
521 }
522 let chip = &mut chips[position];
523 chip.count += 1;
524 chip.mine |= my_user_id.is_some() && reaction.user_id.as_deref() == my_user_id;
525 chip.reactors.push(Reactor {
526 user_id: reaction.user_id.clone(),
527 name: reactor_name(reaction, context),
528 created_at: reaction.created_at,
529 });
530 }
531 for (chip, shown) in chips.iter_mut().zip(variants) {
532 chip.label = shown.concat();
533 }
534 chips
535}
536
537fn reactor_name(reaction: &ReactionInfo, context: &RowContext) -> String {
538 reaction
539 .user_name
540 .clone()
541 .or_else(|| {
542 reaction
543 .user_id
544 .as_ref()
545 .and_then(|user_id| context.names.get(user_id).cloned())
546 })
547 .unwrap_or_else(|| UNKNOWN_REACTOR.to_owned())
548}
549
550const REPLY_EXCERPT_CHARS: usize = 90;
551
552pub fn message_text(record: &MessageRecord) -> String {
553 let own_spans: Vec<Span> = message_spans(record)
554 .into_iter()
555 .filter(|span| !matches!(span, Span::Quote { .. }))
556 .collect();
557 strip_image_placeholders(layout_blocks(&own_spans))
558 .into_iter()
559 .filter_map(|block| block.markdown())
560 .chain(forwarded_texts(record))
561 .collect::<Vec<_>>()
562 .join("\n")
563}
564
565/// The message as the composer edits it, formatting kept.
566pub fn message_draft(record: &MessageRecord) -> Draft {
567 let own_spans: Vec<Span> = message_spans(record)
568 .into_iter()
569 .filter(|span| !matches!(span, Span::Quote { .. }))
570 .collect();
571 Draft::from_spans(&own_spans).trimmed()
572}
573
574pub fn reply_excerpt(record: &MessageRecord) -> String {
575 let own_spans: Vec<Span> = message_spans(record)
576 .into_iter()
577 .filter(|span| !matches!(span, Span::Quote { .. }))
578 .collect();
579 let text = strip_image_placeholders(layout_blocks(&own_spans))
580 .into_iter()
581 .find_map(|block| block.first_line())
582 .unwrap_or_default();
583 let first_line = text.lines().map(str::trim).find(|line| !line.is_empty());
584 let excerpt = match first_line {
585 Some(line) => line.to_owned(),
586 None if let Some(line) = forwarded_texts(record)
587 .iter()
588 .flat_map(|text| text.lines())
589 .map(str::trim)
590 .find(|line| !line.is_empty()) =>
591 {
592 line.to_owned()
593 }
594 None if !images(record).is_empty() => "Image".to_owned(),
595 None if let Some(line) = card_texts(record)
596 .iter()
597 .flat_map(|text| text.lines())
598 .next() =>
599 {
600 line.to_owned()
601 }
602 None => files(record)
603 .into_iter()
604 .next()
605 .map_or_else(|| "Message".to_owned(), |card| card.name),
606 };
607 if excerpt.chars().count() > REPLY_EXCERPT_CHARS {
608 let cut: String = excerpt.chars().take(REPLY_EXCERPT_CHARS).collect();
609 format!("{}...", cut.trim_end())
610 } else {
611 excerpt
612 }
613}
614
615pub struct RowContext {
616 pub offset: FixedOffset,
617 pub today: NaiveDate,
618 pub my_user_id: Option<String>,
619 pub names: HashMap<String, String>,
620 pub pending_reactions: PendingReactions,
621 pub card_overrides: HashMap<String, CardOverride>,
622 pub translation: TranslationContext,
623 pub skin_tone: u8,
624 pub meeting: MeetingInfo,
625}
626
627fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {
628 let mut visible = reactions(record);
629 apply_pending_reactions(
630 &mut visible,
631 context.pending_reactions.get(&record.message_id),
632 context.my_user_id.as_deref(),
633 Utc::now(),
634 );
635 visible
636}
637
638fn call_row(
639 record: &MessageRecord,
640 event: &CallEvent,
641 context: &RowContext,
642 timeline: &CallTimeline,
643) -> MessageRow {
644 let my_user_id = context.my_user_id.as_deref();
645 let time = clock_label(record.created_at, context.offset);
646 let names = CallNames {
647 my_user_id,
648 names: &context.names,
649 };
650 let author = event
651 .initiator_name
652 .clone()
653 .or_else(|| {
654 event
655 .initiator_id
656 .as_ref()
657 .and_then(|user_id| context.names.get(user_id).cloned())
658 })
659 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
660 let card = call_card(
661 CallSource {
662 event,
663 message_id: &record.message_id,
664 created_at: record.created_at,
665 time: &time,
666 },
667 &names,
668 &CallClock {
669 offset: context.offset,
670 today: context.today,
671 meeting: &context.meeting,
672 },
673 timeline,
674 );
675 event_row(
676 record,
677 context,
678 EventAuthor {
679 sender_id: event.initiator_id.clone(),
680 name: author,
681 own: event.initiated_by(my_user_id),
682 },
683 card,
684 time,
685 )
686}
687
688fn roster_row(record: &MessageRecord, event: &RosterEvent, context: &RowContext) -> MessageRow {
689 let my_user_id = context.my_user_id.as_deref();
690 let names = CallNames {
691 my_user_id,
692 names: &context.names,
693 };
694 let card = roster_card(
695 event,
696 record.created_at,
697 &names,
698 &CallClock {
699 offset: context.offset,
700 today: context.today,
701 meeting: &context.meeting,
702 },
703 );
704 let author = event
705 .initiator_name
706 .clone()
707 .or_else(|| {
708 event
709 .initiator_id
710 .as_ref()
711 .and_then(|user_id| context.names.get(user_id).cloned())
712 })
713 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
714 let own = my_user_id.is_some() && event.initiator_id.as_deref() == my_user_id;
715 event_row(
716 record,
717 context,
718 EventAuthor {
719 sender_id: event.initiator_id.clone(),
720 name: author,
721 own,
722 },
723 card,
724 clock_label(record.created_at, context.offset),
725 )
726}
727
728struct EventAuthor {
729 sender_id: Option<String>,
730 name: String,
731 own: bool,
732}
733
734fn event_row(
735 record: &MessageRecord,
736 context: &RowContext,
737 author: EventAuthor,
738 card: CallCard,
739 time: String,
740) -> MessageRow {
741 MessageRow {
742 key: record.message_id.clone(),
743 conversation_id: record.conversation_id.clone(),
744 sender_id: author.sender_id,
745 application_id: None,
746 created_at: record.created_at,
747 series: Series::default(),
748 author: author.name,
749 day_header: Some(format::day_label(
750 record
751 .created_at
752 .with_timezone(&context.offset)
753 .date_naive(),
754 context.today,
755 )),
756 blocks: Vec::new(),
757 jumbo: None,
758 edited: false,
759 deleted: false,
760 reactions: Vec::new(),
761 images: Vec::new(),
762 local_images: Vec::new(),
763 files: Vec::new(),
764 link_preview: None,
765 meeting_link: None,
766 adaptive_cards: Vec::new(),
767 subject: None,
768 banner: None,
769 importance: MessageImportance::Normal,
770 new_marker: false,
771 reply_root: None,
772 delivery: Delivery::Delivered,
773 receipt: Receipt::Hidden,
774 receipt_label: None,
775 own: author.own,
776 forwarded: false,
777 translation: None,
778 call: Some(card),
779 time,
780 }
781}
782
783const QUOTE_LINES: usize = 5;
784
785pub fn quoted_texts(records: &[MessageRecord]) -> HashMap<String, String> {
786 let wanted: std::collections::HashSet<String> = records
787 .iter()
788 .flat_map(quotes)
789 .map(|quote| quote.message_id)
790 .collect();
791 records
792 .iter()
793 .filter(|record| !record.deleted && wanted.contains(&record.message_id))
794 .map(|record| {
795 let mut text = readable_text(record);
796 if text.is_empty() {
797 text = forwarded_texts(record).join("\n");
798 }
799 let lines: Vec<&str> = text.lines().filter(|line| !line.trim().is_empty()).collect();
800 let mut shown = lines.iter().take(QUOTE_LINES).copied().collect::<Vec<_>>().join("\n");
801 if lines.len() > QUOTE_LINES {
802 shown.push_str(" …");
803 }
804 (record.message_id.clone(), shown)
805 })
806 .collect()
807}
808
809fn forward_header(forward: &ForwardInfo, context: &RowContext) -> ForwardHeader {
810 ForwardHeader {
811 sender: forward
812 .sender_id
813 .as_ref()
814 .and_then(|user_id| context.names.get(user_id).cloned()),
815 time: forward
816 .sent_at
817 .map(|time| format::post_time_label(time, context.today, context.offset)),
818 }
819}
820
821/// User ids a row needs a name for beyond its author: original senders of forwards.
822pub fn forward_sender_ids(records: &[MessageRecord]) -> Vec<String> {
823 let mut user_ids: Vec<String> = Vec::new();
824 for user_id in records
825 .iter()
826 .flat_map(forwards)
827 .filter_map(|forward| forward.sender_id)
828 {
829 if !user_ids.contains(&user_id) {
830 user_ids.push(user_id);
831 }
832 }
833 user_ids
834}
835
836pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
837 message_row_with(record, context, &HashMap::new())
838}
839
840fn message_row_with(
841 record: &MessageRecord,
842 context: &RowContext,
843 quoted: &HashMap<String, String>,
844) -> MessageRow {
845 if let Some(event) = call_event(record) {
846 let events = [Some(event.clone())];
847 return call_row(record, &event, context, &CallTimeline::new(&events));
848 }
849 if let Some(event) = roster_event(record) {
850 return roster_row(record, &event, context);
851 }
852 let local = record.created_at.with_timezone(&context.offset);
853 let images = images(record);
854 let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id;
855 let translation = context.translation.resolve(record, own);
856 let forward_header = |forward: &ForwardInfo| forward_header(forward, context);
857 let blocks = if record.deleted {
858 vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]
859 } else if let Some(html) = &translation.translated_html {
860 layout_blocks(&translated_spans(record, html, &forward_header))
861 } else {
862 layout_blocks(&linked_message_spans_with(
863 record,
864 &|id| quoted.get(id).cloned(),
865 &forward_header,
866 ))
867 };
868 let blocks = if images.is_empty() {
869 blocks
870 } else {
871 strip_image_placeholders(blocks)
872 };
873 MessageRow {
874 key: record.message_id.clone(),
875 conversation_id: record.conversation_id.clone(),
876 sender_id: record.sender_id.clone(),
877 application_id: record.sender_application_id.clone(),
878 created_at: record.created_at,
879 series: Series::default(),
880 author: record
881 .sender_name
882 .clone()
883 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
884 time: clock_label(record.created_at, context.offset),
885 day_header: Some(format::day_label(local.date_naive(), context.today)),
886 blocks,
887 jumbo: (!record.deleted && !is_forwarded(record))
888 .then(|| jumbo_emoji(&record.body_html))
889 .flatten(),
890 edited: record.edited_at.is_some() && !record.deleted,
891 deleted: record.deleted,
892 reactions: reaction_chips(&visible_reactions(record, context), context),
893 images,
894 local_images: Vec::new(),
895 files: files(record),
896 link_preview: link_preview(record),
897 meeting_link: (!record.deleted)
898 .then(|| meeting_link_in_html(&record.body_html))
899 .flatten(),
900 adaptive_cards: match context.card_overrides.get(&record.message_id) {
901 Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
902 _ => adaptive_cards(record),
903 },
904 subject: record.subject.clone(),
905 banner: AnnouncementBanner::from_attachments(&attachments(record)),
906 importance: if record.deleted {
907 MessageImportance::Normal
908 } else {
909 record.importance
910 },
911 new_marker: false,
912 reply_root: record.reply_to_id.clone(),
913 delivery: Delivery::Delivered,
914 receipt: Receipt::Hidden,
915 receipt_label: None,
916 own,
917 forwarded: is_forwarded(record),
918 translation: translation.line,
919 call: None,
920 }
921}
922
923pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {
924 let mut rows = Vec::with_capacity(records.len() + 1);
925 if has_older {
926 rows.push(Row::LoadOlder);
927 }
928 let events: Vec<Option<CallEvent>> = records.iter().map(call_event).collect();
929 let timeline = CallTimeline::with_records(&events, &records.iter().collect::<Vec<_>>());
930 let mut previous_day: Option<NaiveDate> = None;
931 let quoted = quoted_texts(records);
932 for (index, (record, event)) in records.iter().zip(&events).enumerate() {
933 if timeline.hides(index) {
934 continue;
935 }
936 let mut row = match event {
937 Some(event) => call_row(record, event, context, &timeline),
938 None => message_row_with(record, context, &quoted),
939 };
940 if let Some(call) = row.call.as_mut() {
941 call.started &= timeline.is_live_start(index);
942 }
943 let day = record
944 .created_at
945 .with_timezone(&context.offset)
946 .date_naive();
947 if previous_day == Some(day) {
948 row.day_header = None;
949 }
950 previous_day = Some(day);
951 rows.push(Row::Message(Box::new(row)));
952 }
953 assign_series(&mut rows);
954 rows
955}
956
957pub fn group_threads(records: &[MessageRecord]) -> Vec<Thread> {
958 let mut threads: Vec<Thread> = Vec::new();
959 let mut index_by_root: BTreeMap<&str, usize> = BTreeMap::new();
960 for record in records.iter().filter(|record| record.reply_to_id.is_none()) {
961 index_by_root.insert(record.message_id.as_str(), threads.len());
962 threads.push(Thread {
963 root_id: record.message_id.clone(),
964 reply_ids: Vec::new(),
965 });
966 }
967 for record in records {
968 let Some(root_id) = record.reply_to_id.as_deref() else {
969 continue;
970 };
971 if let Some(&index) = index_by_root.get(root_id) {
972 threads[index].reply_ids.push(record.message_id.clone());
973 }
974 }
975 threads
976}
977
978fn last_activity(thread: &Thread, by_id: &BTreeMap<&str, &MessageRecord>) -> DateTime<Utc> {
979 thread
980 .reply_ids
981 .iter()
982 .chain(std::iter::once(&thread.root_id))
983 .filter_map(|id| by_id.get(id.as_str()))
984 .map(|record| record.created_at)
985 .max()
986 .unwrap_or_default()
987}
988
989fn post_message_row(
990 record: &MessageRecord,
991 context: &RowContext,
992 timeline: &CallTimeline,
993) -> MessageRow {
994 let mut row = match call_event(record) {
995 Some(event) => call_row(record, &event, context, timeline),
996 None => message_row(record, context),
997 };
998 row.day_header = None;
999 row.time = format::post_time_label(record.created_at, context.today, context.offset);
1000 row
1001}
1002
1003fn meeting_root_row(
1004 root: &MessageRecord,
1005 started: &CallEvent,
1006 ended: Option<(&MessageRecord, CallEvent)>,
1007 context: &RowContext,
1008 timeline: &CallTimeline,
1009) -> MessageRow {
1010 let Some((ended_record, ended_event)) = ended else {
1011 let mut row = post_message_row(root, context, timeline);
1012 if let Some(call) = row.call.as_mut() {
1013 call.started = !timeline.finished(&started.call_id);
1014 }
1015 return row;
1016 };
1017 let mut summary = CallEvent {
1018 initiator_id: started.initiator_id.clone(),
1019 initiator_name: started
1020 .initiator_name
1021 .clone()
1022 .or(ended_event.initiator_name.clone()),
1023 ..ended_event
1024 };
1025 summary.call_type = started.call_type;
1026 let mut row = call_row(ended_record, &summary, context, timeline);
1027 row.key = root.message_id.clone();
1028 row.created_at = root.created_at;
1029 row.reply_root = None;
1030 row.day_header = None;
1031 row.time = format::post_time_label(root.created_at, context.today, context.offset);
1032 row
1033}
1034
1035fn distinct_names<'a>(records: impl Iterator<Item = &'a MessageRecord>) -> Vec<String> {
1036 let mut names: Vec<String> = Vec::new();
1037 for record in records.filter(|record| record.call_event_json.is_none()) {
1038 let name = record
1039 .sender_name
1040 .clone()
1041 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
1042 if !names.contains(&name) {
1043 names.push(name);
1044 }
1045 }
1046 names
1047}
1048
1049fn post_row(
1050 root: MessageRow,
1051 mut replies: Vec<&MessageRecord>,
1052 context: &RowContext,
1053 timeline: &CallTimeline,
1054) -> PostRow {
1055 replies.sort_by_key(|reply| reply.created_at);
1056 let hidden = replies.len().saturating_sub(POST_VISIBLE_REPLIES);
1057 PostRow {
1058 root,
1059 hidden_reply_count: hidden,
1060 hidden_repliers: distinct_names(replies[..hidden].iter().copied()),
1061 replies: replies[hidden..]
1062 .iter()
1063 .map(|reply| post_message_row(reply, context, timeline))
1064 .collect(),
1065 is_new: false,
1066 }
1067}
1068
1069/// Channel feed: Teams shows a Meet now meeting as its own post and keeps the other call notices
1070/// inside the thread; a saved recording stays visible as a reply.
1071fn shows_in_feed(record: &MessageRecord, event: Option<&CallEvent>) -> bool {
1072 match event {
1073 None => true,
1074 Some(event) if record.reply_to_id.is_none() => event.phase == CallPhase::Started,
1075 Some(event) => event.phase == CallPhase::RecordingSaved,
1076 }
1077}
1078
1079pub fn thread_list_rows(
1080 records: &[MessageRecord],
1081 context: &RowContext,
1082 has_older: bool,
1083) -> Vec<Row> {
1084 let events: Vec<Option<CallEvent>> = records.iter().map(call_event).collect();
1085 let timeline = CallTimeline::new(&events);
1086 let ended: HashMap<&str, (&MessageRecord, &CallEvent)> = records
1087 .iter()
1088 .zip(&events)
1089 .filter_map(|(record, event)| {
1090 let event = event
1091 .as_ref()
1092 .filter(|event| event.phase == CallPhase::Ended)?;
1093 Some((event.call_id.as_str(), (record, event)))
1094 })
1095 .collect();
1096 let by_id: BTreeMap<&str, (&MessageRecord, Option<&CallEvent>)> = records
1097 .iter()
1098 .zip(&events)
1099 .filter(|(record, event)| shows_in_feed(record, event.as_ref()))
1100 .map(|(record, event)| (record.message_id.as_str(), (record, event.as_ref())))
1101 .collect();
1102 let records_by_id: BTreeMap<&str, &MessageRecord> = by_id
1103 .iter()
1104 .map(|(id, (record, _))| (*id, *record))
1105 .collect();
1106 let mut threads = group_threads(records);
1107 threads.sort_by_key(|thread| std::cmp::Reverse(last_activity(thread, &records_by_id)));
1108 let mut rows: Vec<Row> = threads
1109 .iter()
1110 .filter_map(|thread| {
1111 let (root, root_event) = by_id.get(thread.root_id.as_str())?;
1112 let root_row = match root_event {
1113 Some(started) => meeting_root_row(
1114 root,
1115 started,
1116 ended
1117 .get(started.call_id.as_str())
1118 .map(|(record, event)| (*record, (*event).clone())),
1119 context,
1120 &timeline,
1121 ),
1122 None => post_message_row(root, context, &timeline),
1123 };
1124 let replies = thread
1125 .reply_ids
1126 .iter()
1127 .filter_map(|id| records_by_id.get(id.as_str()).copied())
1128 .collect();
1129 Some(Row::Post(Box::new(post_row(
1130 root_row, replies, context, &timeline,
1131 ))))
1132 })
1133 .collect();
1134 if has_older {
1135 rows.push(Row::LoadOlder);
1136 }
1137 rows
1138}
1139
1140pub fn place_local_rows(rows: &mut Vec<Row>, local: Vec<MessageRow>) {
1141 for message in local {
1142 let Some(root_id) = message.reply_root.clone() else {
1143 rows.insert(0, Row::Post(Box::new(PostRow::local(message))));
1144 continue;
1145 };
1146 let position = rows
1147 .iter()
1148 .position(|row| matches!(row, Row::Post(post) if post.root.key == root_id));
1149 if let Some(position) = position {
1150 let mut row = rows.remove(position);
1151 if let Row::Post(post) = &mut row {
1152 post.replies.push(message);
1153 }
1154 rows.insert(0, row);
1155 }
1156 }
1157}
1158
1159pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> {
1160 let members: Vec<MessageRecord> = records
1161 .iter()
1162 .filter(|record| {
1163 record.message_id == root_id || record.reply_to_id.as_deref() == Some(root_id)
1164 })
1165 .cloned()
1166 .collect();
1167 flat_rows(&members, context, false)
1168}
1169
1170#[derive(Debug, Clone, PartialEq, Eq)]
1171pub struct Splice {
1172 pub range: Range<usize>,
1173 pub count: usize,
1174}
1175
1176pub fn diff_keys(old: &[String], new: &[String]) -> Option<Splice> {
1177 if old == new {
1178 return None;
1179 }
1180 let prefix = old
1181 .iter()
1182 .zip(new)
1183 .take_while(|(left, right)| left == right)
1184 .count();
1185 let suffix = old[prefix..]
1186 .iter()
1187 .rev()
1188 .zip(new[prefix..].iter().rev())
1189 .take_while(|(left, right)| left == right)
1190 .count();
1191 Some(Splice {
1192 range: prefix..old.len() - suffix,
1193 count: new.len() - prefix - suffix,
1194 })
1195}
1196
1197pub fn changed_indices(old: &[Row], new: &[Row]) -> Vec<usize> {
1198 let prefix = old
1199 .iter()
1200 .zip(new)
1201 .take_while(|(left, right)| left.key() == right.key())
1202 .count();
1203 let suffix = old[prefix..]
1204 .iter()
1205 .rev()
1206 .zip(new[prefix..].iter().rev())
1207 .take_while(|(left, right)| left.key() == right.key())
1208 .count();
1209 let mut changed: Vec<usize> = (0..prefix)
1210 .filter(|&index| old[index] != new[index])
1211 .collect();
1212 changed.extend((0..suffix).filter_map(|offset| {
1213 let old_index = old.len() - 1 - offset;
1214 let new_index = new.len() - 1 - offset;
1215 (old[old_index] != new[new_index]).then_some(new_index)
1216 }));
1217 changed
1218}
1219
1220#[cfg(test)]
1221mod tests {
1222 use chrono::TimeZone;
1223 use teams_core::CallType;
1224
1225 use super::*;
1226
1227 #[test]
1228 fn the_receipt_label_names_who_saw_a_group_message() {
1229 let reader = |name: &str| teams_core::ReceiptReader {
1230 name: name.into(),
1231 at: Utc::now(),
1232 };
1233 let read = |readers: Vec<teams_core::ReceiptReader>, total_others| {
1234 receipt_label(&teams_core::ReceiptState::Read { readers, total_others })
1235 };
1236 assert_eq!(read(vec![reader("Bea")], 1).as_deref(), Some("Seen"));
1237 assert_eq!(read(vec![reader("Bea"), reader("Cy")], 2).as_deref(), Some("Seen by everyone"));
1238 assert_eq!(read(vec![reader("Bea")], 3).as_deref(), Some("Seen by Bea"));
1239 assert_eq!(receipt_label(&teams_core::ReceiptState::Sent).as_deref(), Some("Sent"));
1240 assert_eq!(receipt_label(&teams_core::ReceiptState::Unknown), None);
1241 }
1242
1243 fn record(id: &str, reply_to: Option<&str>, hour: u32, day: u32) -> MessageRecord {
1244 MessageRecord {
1245 conversation_id: "c".into(),
1246 message_id: id.into(),
1247 reply_to_id: reply_to.map(str::to_owned),
1248 sender_id: Some("u".into()),
1249 sender_name: Some("Author".into()),
1250 sender_application_id: None,
1251 links_json: "[]".to_owned(),
1252 created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),
1253 edited_at: None,
1254 deleted: false,
1255 body_html: format!("<p>text {id}</p>"),
1256 attachments_json: "[]".into(),
1257 reactions_json: "[]".into(),
1258 mentions_json: "[]".into(),
1259 subject: None,
1260 call_event_json: None,
1261 importance: Default::default(),
1262 }
1263 }
1264
1265 #[test]
1266 fn a_quote_shows_the_lines_of_the_quoted_message_when_it_is_loaded() {
1267 let mut quoted = record("q1", None, 8, 6);
1268 quoted.body_html = "<p>first link</p><p>second link</p>".into();
1269 let mut answer = record("a1", None, 9, 6);
1270 answer.body_html = "<attachment id=\"q1\"></attachment><p>please again</p>".into();
1271 answer.attachments_json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"id":"q1","quote":{"message_id":"q1","preview":"first link second link","sender_name":"Robin"}}]"#.into();
1272 let rows = flat_rows(&[quoted, answer], &context(), false);
1273 let reply = rows
1274 .iter()
1275 .find_map(|row| match row {
1276 Row::Message(row) if row.key == "a1" => Some(row.blocks.clone()),
1277 _ => None,
1278 })
1279 .unwrap();
1280 let Some(Block::Reply { children, .. }) = reply.first() else { panic!("{reply:?}") };
1281 let text = format!("{children:?}");
1282 assert!(text.contains(r"first link\nsecond link"), "{text}");
1283 }
1284
1285 fn own_reaction(reaction_type: &str) -> ReactionInfo {
1286 ReactionInfo {
1287 reaction_type: reaction_type.into(),
1288 user_id: Some("me".into()),
1289 user_name: None,
1290 created_at: None,
1291 }
1292 }
1293
1294 #[test]
1295 fn setting_a_reaction_is_idempotent_and_only_touches_mine() {
1296 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
1297 let other = ReactionInfo {
1298 user_id: Some("them".into()),
1299 ..own_reaction("like")
1300 };
1301 let mut reactions = vec![other.clone()];
1302 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now);
1303 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now);
1304 assert_eq!(reactions.len(), 2);
1305 assert_eq!(reactions[1].reaction_type, "like");
1306 assert_eq!(reactions[1].user_id.as_deref(), Some("me"));
1307 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now);
1308 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now);
1309 assert_eq!(reactions, vec![other]);
1310 }
1311
1312 #[test]
1313 fn setting_matches_legacy_names_and_variation_selectors() {
1314 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
1315 let mut reactions = vec![own_reaction("heart")];
1316 assert!(has_own_reaction(&reactions, "\u{2764}\u{FE0F}", Some("me")));
1317 set_own_reaction(&mut reactions, "\u{2764}\u{FE0F}", Some("me"), false, now);
1318 assert!(reactions.is_empty());
1319 set_own_reaction(&mut reactions, "\u{1F389}", Some("me"), true, now);
1320 assert_eq!(reactions[0].reaction_type, "\u{1F389}");
1321 }
1322
1323 #[test]
1324 fn setting_without_a_known_user_never_matches() {
1325 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
1326 let mut reactions = Vec::new();
1327 set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now);
1328 set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now);
1329 assert_eq!(reactions.len(), 2);
1330 }
1331
1332 #[test]
1333 fn pending_reactions_overlay_the_stored_ones() {
1334 let mut stored = record("a", None, 8, 6);
1335 stored.reactions_json = serde_json::to_string(&[own_reaction("like")]).unwrap();
1336 let mut context = context();
1337 context.my_user_id = Some("me".into());
1338 context.pending_reactions.insert(
1339 "a".into(),
1340 vec![("\u{1F44D}".into(), false), ("\u{1F389}".into(), true)],
1341 );
1342 let chips = message_row(&stored, &context).reactions;
1343 assert_eq!(chips.len(), 1);
1344 assert_eq!(chips[0].reaction_type, "\u{1F389}");
1345 assert!(chips[0].mine);
1346 }
1347
1348 #[test]
1349 fn org_emoji_shows_its_name_and_loads_its_image() {
1350 let key = "absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8";
1351 assert_eq!(reaction_text(key), ":absolute-cinema:");
1352 assert_eq!(reaction_text("like"), "\u{1F44D}");
1353 let image = custom_emoji_image(key).expect("image");
1354 assert!(image.url.ends_with("/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim"));
1355 assert_eq!(custom_emoji_image("like"), None);
1356 }
1357
1358 #[test]
1359 fn reaction_type_maps_classic_glyphs_to_names() {
1360 assert_eq!(reaction_type_for("\u{1F44D}"), "like");
1361 assert_eq!(reaction_type_for("\u{2764}\u{FE0F}"), "heart");
1362 assert_eq!(reaction_type_for("\u{1F389}"), "\u{1F389}");
1363 assert_eq!(reaction_glyph("like"), reaction_glyph("\u{1F44D}"));
1364 assert_eq!(reaction_glyph("heart"), reaction_glyph("\u{2764}\u{FE0F}"));
1365 assert_eq!(api_reaction(&reaction_glyph("heart")), "\u{2764}\u{FE0F}");
1366 assert_eq!(api_reaction(&reaction_glyph("like")), "\u{1F44D}");
1367 }
1368
1369 #[test]
1370 fn forwarded_messages_are_detected_by_the_forward_blockquote() {
1371 let mut forwarded = record("f", None, 8, 6);
1372 forwarded.body_html =
1373 r#"<p>fyi</p><blockquote itemscope="" itemtype="http://schema.skype.com/Forward" itemid="1">text</blockquote>"#.into();
1374 assert!(message_row(&forwarded, &context()).forwarded);
1375 forwarded.body_html =
1376 r#"<blockquote itemtype="http://schema.skype.com/Reply">text</blockquote>"#.into();
1377 assert!(!message_row(&forwarded, &context()).forwarded);
1378 forwarded.body_html =
1379 r#"<blockquote itemtype="http://schema.skype.com/Forward">text</blockquote>"#.into();
1380 forwarded.deleted = true;
1381 assert!(!message_row(&forwarded, &context()).forwarded);
1382 }
1383
1384 #[test]
1385 fn a_graph_forward_shows_the_original_sender_and_text_in_a_quote() {
1386 let mut forwarded = record("f", None, 8, 6);
1387 forwarded.body_html = r#"<attachment id="9"></attachment>"#.into();
1388 forwarded.attachments_json = serde_json::json!([{
1389 "content_type": "forwardedMessageReference",
1390 "name": null, "url": null, "text": null, "id": "9",
1391 "content": serde_json::json!({
1392 "originalMessageId": "9",
1393 "originalMessageContent": "<p>original words</p>",
1394 "originalSentDateTime": "2026-10-06T07:00:00.000+00:00",
1395 "originalMessageSender": {"user": {"id": "orig", "displayName": null}}
1396 }).to_string()
1397 }])
1398 .to_string();
1399 let mut context = context();
1400 context.names.insert("orig".into(), "Priya Nair".into());
1401 let row = message_row(&forwarded, &context);
1402 assert!(row.forwarded);
1403 assert!(row.jumbo.is_none());
1404 let [Block::Quote(children)] = row.blocks.as_slice() else {
1405 panic!("expected one forward quote, got {:?}", row.blocks);
1406 };
1407 let lines: Vec<String> = children.iter().filter_map(Block::markdown).collect();
1408 assert!(lines[0].contains("Priya Nair Yesterday 07:00"), "{lines:?}");
1409 assert!(lines.iter().any(|line| line.contains("original words")), "{lines:?}");
1410 assert_eq!(reply_excerpt(&forwarded), "original words");
1411 assert_eq!(message_text(&forwarded), "original words");
1412 }
1413
1414 #[test]
1415 fn editing_loads_the_message_formatted_without_its_reply_quote() {
1416 let mut edited = record("a", None, 8, 6);
1417 edited.body_html =
1418 "<blockquote itemtype=\"http://schema.skype.com/Reply\">old</blockquote>\
1419 <p><b>Plan</b> for <a href=\"https://x.test\">today</a></p>\
1420 <ol><li>one</li><li>two</li></ol>"
1421 .into();
1422 let draft = message_draft(&edited);
1423 assert_eq!(draft.text(), "Plan for today\n1. one\n2. two");
1424 assert_eq!(
1425 draft.to_html(),
1426 "<b>Plan</b> for <a href=\"https://x.test\">today</a><ol><li>one</li><li>two</li></ol>"
1427 );
1428 }
1429
1430 #[test]
1431 fn reply_excerpt_uses_the_first_line_or_the_attachment() {
1432 let mut text = record("a", None, 8, 6);
1433 text.body_html = "<p>first line</p><p>second</p>".into();
1434 assert_eq!(reply_excerpt(&text), "first line");
1435 let mut quoted = record("q", None, 8, 6);
1436 quoted.body_html = r#"<blockquote itemtype="http://schema.skype.com/Reply">Jonas<br>old text</blockquote><p>my answer</p>"#.into();
1437 assert_eq!(reply_excerpt(&quoted), "my answer");
1438 let mut image = record("b", None, 8, 6);
1439 image.body_html = "<img src=\"u\">".into();
1440 assert_eq!(reply_excerpt(&image), "Image");
1441 let mut long = record("c", None, 8, 6);
1442 long.body_html = format!("<p>{}</p>", "x".repeat(200));
1443 assert!(reply_excerpt(&long).ends_with("..."));
1444 assert_eq!(
1445 reply_excerpt(&long).chars().count(),
1446 REPLY_EXCERPT_CHARS + 3
1447 );
1448 }
1449
1450 fn context() -> RowContext {
1451 RowContext {
1452 offset: FixedOffset::east_opt(0).unwrap(),
1453 today: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(),
1454 my_user_id: None,
1455 names: HashMap::new(),
1456 pending_reactions: HashMap::new(),
1457 card_overrides: HashMap::new(),
1458 translation: TranslationContext::default(),
1459 skin_tone: 0,
1460 meeting: MeetingInfo::default(),
1461 }
1462 }
1463
1464 fn keys(rows: &[Row]) -> Vec<String> {
1465 rows.iter().map(|row| row.key().to_owned()).collect()
1466 }
1467
1468 fn translation_context(shown: bool) -> RowContext {
1469 use crate::translation::CachedTranslation;
1470 let mut context = context();
1471 context.translation.enabled = true;
1472 context.translation.target = "en".into();
1473 context.translation.stamps.insert(
1474 "a".into(),
1475 "languages=fr:100;length:80;&detector=Bling".into(),
1476 );
1477 context.my_user_id = Some("me".into());
1478 if shown {
1479 context.translation.cached.insert(
1480 ("a".into(), 0),
1481 CachedTranslation {
1482 html: "<p><strong>translated</strong> body</p>".into(),
1483 source: Some("fr".into()),
1484 },
1485 );
1486 context.translation.shown.insert("a".into());
1487 }
1488 context
1489 }
1490
1491 #[test]
1492 fn a_foreign_message_carries_the_offer_and_keeps_its_text() {
1493 let row = message_row(&record("a", None, 8, 6), &translation_context(false));
1494 assert!(matches!(
1495 row.translation,
1496 Some(TranslationLine::Offer { ref language_code, .. }) if language_code == "fr"
1497 ));
1498 assert_eq!(
1499 row.blocks,
1500 layout_blocks(&teams_core::linked_message_spans(&record("a", None, 8, 6)))
1501 );
1502 }
1503
1504 #[test]
1505 fn a_shown_translation_replaces_the_body_and_the_original_comes_back() {
1506 let original = message_row(&record("a", None, 8, 6), &translation_context(false)).blocks;
1507 let translated = message_row(&record("a", None, 8, 6), &translation_context(true));
1508 assert_ne!(translated.blocks, original);
1509 assert_eq!(
1510 translated.translation,
1511 Some(TranslationLine::Translated {
1512 language: Some("French".into()),
1513 showing_original: false
1514 })
1515 );
1516 let mut hidden = translation_context(true);
1517 hidden.translation.shown.clear();
1518 let back = message_row(&record("a", None, 8, 6), &hidden);
1519 assert_eq!(back.blocks, original);
1520 assert_eq!(
1521 back.translation,
1522 Some(TranslationLine::Translated {
1523 language: Some("French".into()),
1524 showing_original: true
1525 })
1526 );
1527 }
1528
1529 #[test]
1530 fn own_messages_get_no_offer() {
1531 let mut own = record("a", None, 8, 6);
1532 own.sender_id = Some("me".into());
1533 assert_eq!(
1534 message_row(&own, &translation_context(false)).translation,
1535 None
1536 );
1537 }
1538
1539 #[test]
1540 fn day_header_only_on_first_message_of_a_day() {
1541 let records = vec![
1542 record("a", None, 8, 6),
1543 record("b", None, 9, 6),
1544 record("c", None, 9, 7),
1545 ];
1546 let rows = flat_rows(&records, &context(), false);
1547 let headers: Vec<Option<String>> = rows
1548 .iter()
1549 .map(|row| match row {
1550 Row::Message(message) => message.day_header.clone(),
1551 Row::LoadOlder
1552 | Row::LoadNewer
1553 | Row::Start(_)
1554 | Row::Skeleton(_)
1555 | Row::Post(_) => None,
1556 })
1557 .collect();
1558 assert_eq!(
1559 headers,
1560 vec![Some("Yesterday".into()), None, Some("Today".into())]
1561 );
1562 }
1563
1564 #[test]
1565 fn load_older_row_only_when_more_exists() {
1566 let records = vec![record("a", None, 8, 6)];
1567 assert_eq!(
1568 keys(&flat_rows(&records, &context(), true))[0],
1569 LOAD_OLDER_KEY
1570 );
1571 assert_eq!(keys(&flat_rows(&records, &context(), false)), vec!["a"]);
1572 }
1573
1574 #[test]
1575 fn threads_group_replies_by_root() {
1576 let records = vec![
1577 record("r1", None, 8, 6),
1578 record("r2", None, 9, 6),
1579 record("x1", Some("r1"), 10, 6),
1580 record("x2", Some("r1"), 11, 6),
1581 record("orphan", Some("missing"), 12, 6),
1582 ];
1583 let threads = group_threads(&records);
1584 assert_eq!(threads.len(), 2);
1585 assert_eq!(threads[0].reply_ids, vec!["x1", "x2"]);
1586 assert!(threads[1].reply_ids.is_empty());
1587 }
1588
1589 fn post_of(row: &Row) -> &PostRow {
1590 let Row::Post(post) = row else {
1591 panic!("post expected")
1592 };
1593 post
1594 }
1595
1596 fn reply_by(id: &str, root: &str, sender: &str, hour: u32) -> MessageRecord {
1597 let mut reply = record(id, Some(root), hour, 6);
1598 reply.sender_name = Some(sender.into());
1599 reply
1600 }
1601
1602 #[test]
1603 fn feed_orders_posts_by_last_activity_newest_first() {
1604 let records = vec![
1605 record("r1", None, 8, 6),
1606 record("r2", None, 9, 6),
1607 record("r3", None, 10, 6),
1608 record("x1", Some("r1"), 11, 6),
1609 ];
1610 let rows = thread_list_rows(&records, &context(), false);
1611 assert_eq!(keys(&rows), vec!["r1", "r3", "r2"]);
1612 }
1613
1614 #[test]
1615 fn feed_puts_load_older_at_the_bottom() {
1616 let records = vec![record("r1", None, 8, 6), record("r2", None, 9, 6)];
1617 let rows = thread_list_rows(&records, &context(), true);
1618 assert_eq!(keys(&rows), vec!["r2", "r1", LOAD_OLDER_KEY]);
1619 }
1620
1621 #[test]
1622 fn post_shows_the_last_three_replies_oldest_first() {
1623 let mut records = vec![record("r1", None, 1, 6)];
1624 for hour in 2..=6 {
1625 records.push(reply_by(&format!("x{hour}"), "r1", "Ada Lovelace", hour));
1626 }
1627 records.reverse();
1628 let rows = thread_list_rows(&records, &context(), false);
1629 let post = post_of(&rows[0]);
1630 let shown: Vec<&str> = post
1631 .replies
1632 .iter()
1633 .map(|reply| reply.key.as_str())
1634 .collect();
1635 assert_eq!(shown, vec!["x4", "x5", "x6"]);
1636 assert_eq!(post.hidden_reply_count, 2);
1637 assert_eq!(post.hidden_repliers, vec!["Ada Lovelace"]);
1638 }
1639
1640 #[test]
1641 fn post_without_hidden_replies_has_no_link() {
1642 let records = vec![
1643 record("r1", None, 1, 6),
1644 reply_by("x1", "r1", "Ada", 2),
1645 reply_by("x2", "r1", "Ben", 3),
1646 reply_by("x3", "r1", "Cy", 4),
1647 ];
1648 let rows = thread_list_rows(&records, &context(), false);
1649 assert_eq!(post_of(&rows[0]).hidden_replies_label(), None);
1650 assert_eq!(post_of(&rows[0]).replies.len(), 3);
1651 }
1652
1653 fn label_for(repliers: &[&str]) -> String {
1654 let mut records = vec![record("r1", None, 1, 6)];
1655 for (index, name) in repliers.iter().enumerate() {
1656 records.push(reply_by(&format!("h{index}"), "r1", name, 2 + index as u32));
1657 }
1658 for index in 0..POST_VISIBLE_REPLIES {
1659 records.push(reply_by(
1660 &format!("v{index}"),
1661 "r1",
1662 "Shown",
1663 20 + index as u32,
1664 ));
1665 }
1666 let rows = thread_list_rows(&records, &context(), false);
1667 post_of(&rows[0]).hidden_replies_label().unwrap()
1668 }
1669
1670 #[test]
1671 fn replies_label_names_one_to_three_people() {
1672 assert_eq!(label_for(&["Anna Meier"]), "1 reply from Anna");
1673 assert_eq!(
1674 label_for(&["Anna Meier", "Anna Meier", "Ben Roth"]),
1675 "3 replies from Anna and Ben"
1676 );
1677 assert_eq!(
1678 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Ben Roth"]),
1679 "4 replies from Anna, Ben and Clara"
1680 );
1681 }
1682
1683 #[test]
1684 fn replies_label_counts_the_others_beyond_three_people() {
1685 assert_eq!(
1686 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox", "Eve Ray"]),
1687 "5 replies from Anna, Ben and 3 others"
1688 );
1689 assert_eq!(
1690 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox"]),
1691 "4 replies from Anna, Ben and 2 others"
1692 );
1693 }
1694
1695 #[test]
1696 fn local_reply_lands_in_its_post_and_local_post_on_top() {
1697 let records = vec![
1698 record("r1", None, 8, 6),
1699 record("r2", None, 9, 6),
1700 reply_by("x1", "r1", "Ada", 10),
1701 ];
1702 let mut rows = thread_list_rows(&records, &context(), true);
1703 let mut pending_reply = message_row(&record("pending-1", Some("r2"), 12, 6), &context());
1704 pending_reply.reply_root = Some("r2".into());
1705 let pending_post = message_row(&record("pending-2", None, 12, 6), &context());
1706 place_local_rows(&mut rows, vec![pending_reply, pending_post]);
1707 assert_eq!(keys(&rows), vec!["pending-2", "r2", "r1", LOAD_OLDER_KEY]);
1708 let replies: Vec<&str> = post_of(&rows[1])
1709 .replies
1710 .iter()
1711 .map(|reply| reply.key.as_str())
1712 .collect();
1713 assert_eq!(replies, vec!["pending-1"]);
1714 }
1715
1716 #[test]
1717 fn local_reply_to_an_unloaded_post_is_not_shown() {
1718 let mut rows = thread_list_rows(&[record("r1", None, 8, 6)], &context(), false);
1719 let mut orphan = message_row(&record("pending-1", Some("gone"), 12, 6), &context());
1720 orphan.reply_root = Some("gone".into());
1721 place_local_rows(&mut rows, vec![orphan]);
1722 assert_eq!(keys(&rows), vec!["r1"]);
1723 }
1724
1725 #[test]
1726 fn subject_reaches_the_post_root() {
1727 let mut with_subject = record("r1", None, 8, 6);
1728 with_subject.subject = Some("Release plan".into());
1729 let rows = thread_list_rows(&[with_subject, record("r2", None, 7, 6)], &context(), false);
1730 assert_eq!(
1731 post_of(&rows[0]).root.subject.as_deref(),
1732 Some("Release plan")
1733 );
1734 assert_eq!(post_of(&rows[1]).root.subject, None);
1735 }
1736
1737 #[test]
1738 fn thread_view_has_root_then_replies() {
1739 let records = vec![
1740 record("r1", None, 8, 6),
1741 record("r2", None, 9, 6),
1742 record("x1", Some("r1"), 10, 6),
1743 ];
1744 assert_eq!(
1745 keys(&thread_rows(&records, "r1", &context())),
1746 vec!["r1", "x1"]
1747 );
1748 }
1749
1750 #[test]
1751 fn reactions_are_counted_in_first_seen_order() {
1752 let reaction = |kind: &str| ReactionInfo {
1753 reaction_type: kind.into(),
1754 user_id: None,
1755 user_name: None,
1756 created_at: None,
1757 };
1758 let chips = reaction_chips(
1759 &[reaction("heart"), reaction("like"), reaction("heart")],
1760 &context(),
1761 );
1762 assert_eq!(chips.len(), 2);
1763 assert_eq!(chips[0].count, 2);
1764 assert_eq!(chips[1].label, reaction_label("like"));
1765 }
1766
1767 #[test]
1768 fn legacy_laugh_and_sad_use_the_teams_glyphs() {
1769 assert_eq!(reaction_label("laugh"), "\u{1F606}");
1770 assert_eq!(reaction_label("sad"), "\u{1F641}");
1771 assert_eq!(reaction_type_for("\u{1F606}"), "laugh");
1772 assert_eq!(reaction_type_for("\u{1F641}"), "sad");
1773 }
1774
1775 #[test]
1776 fn legacy_and_emoji_reactions_share_a_chip() {
1777 let reaction = |kind: &str| ReactionInfo {
1778 reaction_type: kind.into(),
1779 user_id: None,
1780 user_name: Some("Lea".into()),
1781 created_at: None,
1782 };
1783 let chips = reaction_chips(&[reaction("like"), reaction("\u{1F44D}")], &context());
1784 assert_eq!(chips.len(), 1);
1785 assert_eq!(chips[0].count, 2);
1786 }
1787
1788 #[test]
1789 fn skin_tones_share_a_chip_showing_up_to_three_variants() {
1790 let reaction = |kind: &str| ReactionInfo {
1791 reaction_type: kind.into(),
1792 user_id: Some(kind.into()),
1793 user_name: Some("Lea".into()),
1794 created_at: None,
1795 };
1796 let kinds = ["yes-tone2", "👍🏿", "like", "👍🏻", "yes-tone2"];
1797 let mut context = context();
1798 context.skin_tone = 3;
1799 let chips = reaction_chips(&kinds.map(reaction), &context);
1800 assert_eq!(chips.len(), 1);
1801 assert_eq!(chips[0].count, 5);
1802 assert_eq!(chips[0].label, "👍🏼👍🏿👍");
1803 assert_eq!(chips[0].click_glyph, "👍🏽");
1804 }
1805
1806 #[test]
1807 fn own_toned_reaction_matches_the_plain_glyph() {
1808 let mine = ReactionInfo {
1809 reaction_type: "👍🏼".into(),
1810 user_id: Some("me".into()),
1811 user_name: None,
1812 created_at: None,
1813 };
1814 let reactions = vec![mine];
1815 assert!(has_own_reaction(&reactions, "\u{1F44D}", Some("me")));
1816 assert_eq!(
1817 own_reaction_glyph(&reactions, "like", Some("me")).as_deref(),
1818 Some("👍🏼")
1819 );
1820 assert_eq!(reaction_glyph("yes-tone5"), "👍🏿");
1821 }
1822
1823 #[test]
1824 fn reactor_name_falls_back_to_directory_then_unknown() {
1825 let reaction = |user: &str| ReactionInfo {
1826 reaction_type: "like".into(),
1827 user_id: Some(user.into()),
1828 user_name: None,
1829 created_at: None,
1830 };
1831 let mut context = context();
1832 context.names.insert("known".into(), "Priya Nair".into());
1833 let chips = reaction_chips(&[reaction("known"), reaction("other")], &context);
1834 assert_eq!(chips[0].reactors[0].name, "Priya Nair");
1835 assert_eq!(chips[0].reactors[1].name, "Unknown");
1836 }
1837
1838 fn record_by(id: &str, sender: &str, hour: u32, minute: u32, day: u32) -> MessageRecord {
1839 let mut record = record(id, None, hour, day);
1840 record.sender_id = Some(sender.into());
1841 record.created_at = Utc
1842 .with_ymd_and_hms(2026, 10, day, hour, minute, 0)
1843 .unwrap();
1844 record
1845 }
1846
1847 fn series_of(rows: &[Row]) -> Vec<(bool, bool)> {
1848 rows.iter()
1849 .filter_map(|row| match row {
1850 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
1851 Row::LoadOlder
1852 | Row::LoadNewer
1853 | Row::Start(_)
1854 | Row::Skeleton(_)
1855 | Row::Post(_) => None,
1856 })
1857 .collect()
1858 }
1859
1860 #[test]
1861 fn series_joins_same_sender_within_five_minutes() {
1862 let records = vec![
1863 record_by("a", "ada", 9, 0, 7),
1864 record_by("b", "ada", 9, 4, 7),
1865 record_by("c", "ada", 9, 20, 7),
1866 record_by("d", "bob", 9, 21, 7),
1867 record_by("e", "ada", 9, 22, 7),
1868 ];
1869 let rows = flat_rows(&records, &context(), false);
1870 assert_eq!(
1871 series_of(&rows),
1872 vec![
1873 (false, true),
1874 (true, false),
1875 (false, false),
1876 (false, false),
1877 (false, false)
1878 ]
1879 );
1880 }
1881
1882 #[test]
1883 fn series_window_ends_exactly_at_the_gap_constant() {
1884 let gap = SERIES_GAP_MINUTES as u32;
1885 let records = vec![
1886 record_by("a", "ada", 9, 0, 7),
1887 record_by("b", "ada", 9, gap - 1, 7),
1888 record_by("c", "ada", 9, 2 * gap - 1 + gap, 7),
1889 ];
1890 let rows = flat_rows(&records, &context(), false);
1891 assert_eq!(
1892 series_of(&rows),
1893 vec![(false, true), (true, false), (false, false)]
1894 );
1895 }
1896
1897 #[test]
1898 fn series_breaks_at_a_new_day() {
1899 let records = vec![
1900 record_by("a", "ada", 23, 58, 6),
1901 record_by("b", "ada", 0, 1, 7),
1902 ];
1903 let rows = flat_rows(&records, &context(), false);
1904 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
1905 }
1906
1907 fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] {
1908 let corners = bubble_corners(own, Series { has_prev, has_next });
1909 [
1910 corners.top_left,
1911 corners.top_right,
1912 corners.bottom_right,
1913 corners.bottom_left,
1914 ]
1915 }
1916
1917 #[test]
1918 fn corners_match_the_mockup_for_other_senders() {
1919 assert_eq!(corners(false, false, false), [14., 14., 14., 14.]);
1920 assert_eq!(corners(false, false, true), [14., 14., 14., 4.]);
1921 assert_eq!(corners(false, true, true), [4., 14., 14., 4.]);
1922 assert_eq!(corners(false, true, false), [4., 14., 14., 14.]);
1923 }
1924
1925 #[test]
1926 fn corners_match_the_mockup_for_own_messages() {
1927 assert_eq!(corners(true, false, false), [14., 14., 14., 14.]);
1928 assert_eq!(corners(true, false, true), [14., 14., 4., 14.]);
1929 assert_eq!(corners(true, true, true), [14., 4., 4., 14.]);
1930 assert_eq!(corners(true, true, false), [14., 4., 14., 14.]);
1931 }
1932
1933 #[test]
1934 fn own_reaction_is_marked() {
1935 let reaction = |user: &str| ReactionInfo {
1936 reaction_type: "like".into(),
1937 user_id: Some(user.into()),
1938 user_name: None,
1939 created_at: None,
1940 };
1941 let mut context = context();
1942 context.my_user_id = Some("me".into());
1943 let chips = reaction_chips(&[reaction("x"), reaction("me")], &context);
1944 assert!(chips[0].mine);
1945 assert!(!reaction_chips(&[reaction("x")], &context)[0].mine);
1946 }
1947
1948 fn strings(values: &[&str]) -> Vec<String> {
1949 values.iter().map(|value| (*value).to_owned()).collect()
1950 }
1951
1952 #[test]
1953 fn diff_detects_append_prepend_and_replace() {
1954 let base = strings(&["a", "b"]);
1955 assert_eq!(diff_keys(&base, &base), None);
1956 assert_eq!(
1957 diff_keys(&base, &strings(&["a", "b", "c"])),
1958 Some(Splice {
1959 range: 2..2,
1960 count: 1
1961 })
1962 );
1963 assert_eq!(
1964 diff_keys(&base, &strings(&["x", "a", "b"])),
1965 Some(Splice {
1966 range: 0..0,
1967 count: 1
1968 })
1969 );
1970 assert_eq!(
1971 diff_keys(
1972 &strings(&["load-older", "a"]),
1973 &strings(&["load-older", "x", "y", "a"])
1974 ),
1975 Some(Splice {
1976 range: 1..1,
1977 count: 2
1978 })
1979 );
1980 assert_eq!(
1981 diff_keys(&strings(&["load-older", "a"]), &strings(&["a"])),
1982 Some(Splice {
1983 range: 0..1,
1984 count: 0
1985 })
1986 );
1987 assert_eq!(
1988 diff_keys(&base, &strings(&["x"])),
1989 Some(Splice {
1990 range: 0..2,
1991 count: 1
1992 })
1993 );
1994 }
1995
1996 #[test]
1997 fn changed_indices_find_edited_rows() {
1998 let old = flat_rows(
1999 &[record("a", None, 8, 6), record("b", None, 9, 6)],
2000 &context(),
2001 false,
2002 );
2003 let mut edited = record("b", None, 9, 6);
2004 edited.body_html = "<p>changed</p>".into();
2005 let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false);
2006 assert_eq!(changed_indices(&old, &new), vec![1]);
2007 }
2008
2009 fn call_record(id: &str, hour: u32, event: CallEvent) -> MessageRecord {
2010 MessageRecord {
2011 sender_id: None,
2012 sender_name: None,
2013 body_html: String::new(),
2014 call_event_json: Some(event.to_json()),
2015 ..record(id, None, hour, 7)
2016 }
2017 }
2018
2019 fn call_event_of(
2020 phase: CallPhase,
2021 call_id: &str,
2022 initiator: &str,
2023 seconds: Option<u64>,
2024 participants: &[&str],
2025 ) -> CallEvent {
2026 CallEvent {
2027 phase,
2028 call_type: CallType::Call,
2029 call_id: call_id.into(),
2030 duration_seconds: seconds,
2031 initiator_id: Some(initiator.into()),
2032 initiator_name: Some(format!("Name {initiator}")),
2033 participant_ids: participants.iter().map(|id| (*id).to_owned()).collect(),
2034 participant_names: Vec::new(),
2035 recording: None,
2036 }
2037 }
2038
2039 fn call_context() -> RowContext {
2040 let mut context = context();
2041 context.my_user_id = Some("me".into());
2042 context
2043 }
2044
2045 fn call_of(row: &Row) -> &CallCard {
2046 let Row::Message(message) = row else {
2047 panic!("not a message row")
2048 };
2049 message.call.as_ref().expect("call row")
2050 }
2051
2052 #[test]
2053 fn started_call_is_hidden_when_the_same_call_ended() {
2054 let records = [
2055 call_record(
2056 "s1",
2057 9,
2058 call_event_of(CallPhase::Started, "one", "u", None, &[]),
2059 ),
2060 call_record(
2061 "e1",
2062 10,
2063 call_event_of(CallPhase::Ended, "one", "u", Some(723), &["u", "me"]),
2064 ),
2065 call_record(
2066 "s2",
2067 11,
2068 call_event_of(CallPhase::Started, "two", "u", None, &[]),
2069 ),
2070 ];
2071 let rows = flat_rows(&records, &call_context(), false);
2072 assert_eq!(keys(&rows), ["e1", "s2"]);
2073 assert_eq!(call_of(&rows[0]).title, "Call ended");
2074 assert_eq!(call_of(&rows[0]).detail, "12m 3s \u{b7} 10:00");
2075 assert_eq!(call_of(&rows[1]).title, "Call started");
2076 assert_eq!(call_of(&rows[1]).detail, "11:00");
2077 assert!(call_of(&rows[1]).started);
2078 }
2079
2080 #[test]
2081 fn only_the_newest_open_start_can_be_joined() {
2082 let records = [
2083 call_record(
2084 "old",
2085 9,
2086 call_event_of(CallPhase::Started, "lost", "u", None, &[]),
2087 ),
2088 call_record(
2089 "new",
2090 11,
2091 call_event_of(CallPhase::Started, "live", "u", None, &[]),
2092 ),
2093 ];
2094 let rows = flat_rows(&records, &call_context(), false);
2095 assert_eq!(keys(&rows), ["old", "new"]);
2096 assert!(!call_of(&rows[0]).started);
2097 assert!(call_of(&rows[1]).started);
2098 }
2099
2100 #[test]
2101 fn missed_call_needs_an_incoming_call_with_fewer_than_two_participants() {
2102 let rows = flat_rows(
2103 &[
2104 call_record(
2105 "incoming",
2106 9,
2107 call_event_of(CallPhase::Ended, "a", "u", Some(60), &["u"]),
2108 ),
2109 call_record(
2110 "outgoing",
2111 10,
2112 call_event_of(CallPhase::Ended, "b", "me", Some(60), &["me"]),
2113 ),
2114 call_record(
2115 "answered",
2116 11,
2117 call_event_of(CallPhase::Ended, "c", "u", Some(60), &["u", "me"]),
2118 ),
2119 ],
2120 &call_context(),
2121 false,
2122 );
2123 let missed = call_of(&rows[0]);
2124 assert!(missed.missed);
2125 assert_eq!(missed.title, "Missed call");
2126 assert_eq!(missed.detail, "09:00");
2127 assert_eq!(missed.icon, CallIcon::Missed);
2128 let outgoing = call_of(&rows[1]);
2129 assert!(!outgoing.missed);
2130 assert_eq!(outgoing.title, "Call ended");
2131 assert_eq!(outgoing.detail, "1m \u{b7} 10:00");
2132 assert!(!call_of(&rows[2]).missed);
2133 }
2134
2135 #[test]
2136 fn call_side_follows_the_initiator() {
2137 let rows = flat_rows(
2138 &[
2139 call_record(
2140 "mine",
2141 9,
2142 call_event_of(CallPhase::Ended, "a", "me", Some(5), &["me", "u"]),
2143 ),
2144 call_record(
2145 "theirs",
2146 10,
2147 call_event_of(CallPhase::Ended, "b", "u", Some(5), &["me", "u"]),
2148 ),
2149 ],
2150 &call_context(),
2151 false,
2152 );
2153 let sides: Vec<(bool, Option<&str>)> = rows
2154 .iter()
2155 .map(|row| match row {
2156 Row::Message(message) => (message.own, message.sender_id.as_deref()),
2157 _ => unreachable!(),
2158 })
2159 .collect();
2160 assert_eq!(sides, [(true, Some("me")), (false, Some("u"))]);
2161 }
2162
2163 #[test]
2164 fn meeting_events_use_the_video_icon_and_meeting_titles() {
2165 let mut event = call_event_of(CallPhase::Ended, "m", "u", Some(3723), &["u", "me", "x"]);
2166 event.call_type = CallType::Meeting;
2167 let rows = flat_rows(&[call_record("m", 9, event)], &call_context(), false);
2168 let card = call_of(&rows[0]);
2169 assert_eq!(card.title, "Meeting ended");
2170 assert_eq!(card.icon, CallIcon::Video);
2171 assert_eq!(card.detail, "1h 2m 3s \u{b7} 09:00");
2172 }
2173
2174 #[test]
2175 fn call_rows_never_join_a_series() {
2176 let mut records = vec![
2177 record_by("a", "u", 9, 0, 7),
2178 call_record(
2179 "c",
2180 9,
2181 call_event_of(CallPhase::Ended, "x", "u", Some(5), &["u", "me"]),
2182 ),
2183 ];
2184 records.push(record_by("b", "u", 9, 1, 7));
2185 let rows = flat_rows(&records, &call_context(), false);
2186 let series: Vec<Series> = rows
2187 .iter()
2188 .map(|row| match row {
2189 Row::Message(message) => message.series,
2190 _ => unreachable!(),
2191 })
2192 .collect();
2193 assert!(series.iter().all(|series| *series == Series::default()));
2194 }
2195
2196 fn fixture_records(name: &str) -> Vec<MessageRecord> {
2197 let path = format!(
2198 "{}/../core/tests/fixtures/call_events/{name}",
2199 env!("CARGO_MANIFEST_DIR")
2200 );
2201 let thread: graph::Message =
2202 serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
2203 std::iter::once(&thread)
2204 .chain(&thread.replies)
2205 .filter_map(|message| teams_core::message_record("channel", message))
2206 .collect()
2207 }
2208
2209 fn feed_post(row: &Row) -> &PostRow {
2210 let Row::Post(post) = row else {
2211 panic!("not a post")
2212 };
2213 post
2214 }
2215
2216 #[test]
2217 fn posts_from_others_after_the_read_horizon_are_new() {
2218 let records = vec![
2219 record_by("old", "u", 9, 0, 7),
2220 record_by("fresh", "u", 11, 0, 7),
2221 record_by("mine", "me", 12, 0, 7),
2222 ];
2223 let read_until = Utc.with_ymd_and_hms(2026, 10, 7, 10, 0, 0).unwrap();
2224 let new: Vec<(String, bool)> = thread_list_rows(&records, &call_context(), false)
2225 .into_iter()
2226 .map(|row| {
2227 let Row::Post(mut post) = row else {
2228 panic!("not a post")
2229 };
2230 post.mark_new_after(read_until);
2231 (post.root.key.clone(), post.is_new)
2232 })
2233 .collect();
2234 assert!(new.contains(&("fresh".to_owned(), true)));
2235 assert!(new.contains(&("old".to_owned(), false)));
2236 assert!(new.contains(&("mine".to_owned(), false)));
2237 }
2238
2239 #[test]
2240 fn meet_now_root_is_a_post_with_the_ended_meeting_card() {
2241 let records = fixture_records("channel_adhoc_meeting.json");
2242 assert_eq!(records.len(), 2);
2243 let rows = thread_list_rows(&records, &call_context(), false);
2244 assert_eq!(rows.len(), 1);
2245 let post = feed_post(&rows[0]);
2246 assert_eq!(post.root.key, records[0].message_id);
2247 assert!(post.replies.is_empty());
2248 assert_eq!(post.hidden_reply_count, 0);
2249 let card = post.root.call.as_ref().unwrap();
2250 assert_eq!(card.title, "Meeting ended");
2251 assert!(card.detail.starts_with("3h 19m 35s"));
2252 assert!(!card.started);
2253 assert_eq!(card.participants.len(), 3);
2254 assert_eq!(card.extra_participants, 0);
2255 }
2256
2257 #[test]
2258 fn meet_now_root_without_an_end_can_be_joined() {
2259 let mut records = fixture_records("channel_adhoc_meeting.json");
2260 records.truncate(1);
2261 let rows = thread_list_rows(&records, &call_context(), false);
2262 let card = feed_post(&rows[0]).root.call.clone().unwrap();
2263 assert_eq!(card.title, "Meeting started");
2264 assert!(card.started);
2265 }
2266
2267 #[test]
2268 fn scheduled_meeting_post_keeps_call_notices_in_the_thread() {
2269 let mut records = fixture_records("channel_scheduled_meeting.json");
2270 records.sort_by_key(|record| record.created_at);
2271 assert_eq!(records.len(), 3);
2272 let rows = thread_list_rows(&records, &call_context(), false);
2273 let post = feed_post(&rows[0]);
2274 assert!(post.root.call.is_none());
2275 assert!(post.replies.is_empty());
2276 let thread = thread_rows(&records, &records[0].message_id, &call_context());
2277 let titles: Vec<String> = thread
2278 .iter()
2279 .filter_map(|row| match row {
2280 Row::Message(message) => message.call.as_ref().map(|call| call.title.clone()),
2281 _ => None,
2282 })
2283 .collect();
2284 assert_eq!(titles, ["Meeting started", "Meeting ended"]);
2285 }
2286
2287 #[test]
2288 fn saved_recording_shows_in_the_channel_feed_as_a_reply() {
2289 let mut records = fixture_records("channel_adhoc_meeting.json");
2290 let root_id = records[0].message_id.clone();
2291 let page: serde_json::Value = serde_json::from_str(
2292 &std::fs::read_to_string(format!(
2293 "{}/../core/tests/fixtures/call_events/meeting_chat_recording.json",
2294 env!("CARGO_MANIFEST_DIR")
2295 ))
2296 .unwrap(),
2297 )
2298 .unwrap();
2299 for message in page["value"].as_array().unwrap() {
2300 let message: graph::Message = serde_json::from_value(message.clone()).unwrap();
2301 let mut record = teams_core::message_record("channel", &message).unwrap();
2302 record.reply_to_id = Some(root_id.clone());
2303 records.push(record);
2304 }
2305 let rows = thread_list_rows(&records, &call_context(), false);
2306 let post = feed_post(&rows[0]);
2307 assert_eq!(post.replies.len(), 1);
2308 assert_eq!(post.hidden_reply_count, 0);
2309 let saved = post.replies[0].call.as_ref().unwrap();
2310 assert_eq!(saved.icon, CallIcon::Saved);
2311 assert_eq!(
2312 saved.notice.as_ref().unwrap().text,
2313 "Recording has been saved to OneDrive."
2314 );
2315 let thread = thread_rows(&records, &root_id, &call_context());
2316 let calls = thread
2317 .iter()
2318 .filter(|row| matches!(row, Row::Message(message) if message.call.is_some()))
2319 .count();
2320 assert_eq!(calls, 7);
2321 }
2322
2323 #[test]
2324 fn thread_lists_leave_call_events_out() {
2325 let records = [call_record(
2326 "c",
2327 9,
2328 call_event_of(CallPhase::Ended, "x", "u", Some(5), &["u", "me"]),
2329 )];
2330 assert!(thread_list_rows(&records, &call_context(), false).is_empty());
2331 }
2332}