BlueGit

ict rusty-teams

Files

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

rows.rs

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