BlueGit

ict rusty-teams

Files

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

rows.rs

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