BlueGit

ict rusty-teams

Files

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

rows.rs

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