BlueGit

ict rusty-teams

Files

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

rows.rs

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