BlueGit

ict rusty-teams

Files

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

rows.rs

fb874ac1 History
rows.rs 62.5 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, images,
12 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;
506const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward";
507
508pub fn message_text(record: &MessageRecord) -> String {
509 let own_spans: Vec<Span> = message_spans(record)
510 .into_iter()
511 .filter(|span| !matches!(span, Span::Quote { .. }))
512 .collect();
513 strip_image_placeholders(layout_blocks(&own_spans))
514 .into_iter()
515 .filter_map(|block| block.markdown())
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 !images(record).is_empty() => "Image".to_owned(),
542 None if let Some(line) = card_texts(record)
543 .iter()
544 .flat_map(|text| text.lines())
545 .next() =>
546 {
547 line.to_owned()
548 }
549 None => files(record)
550 .into_iter()
551 .next()
552 .map_or_else(|| "Message".to_owned(), |card| card.name),
553 };
554 if excerpt.chars().count() > REPLY_EXCERPT_CHARS {
555 let cut: String = excerpt.chars().take(REPLY_EXCERPT_CHARS).collect();
556 format!("{}...", cut.trim_end())
557 } else {
558 excerpt
559 }
560}
561
562pub struct RowContext {
563 pub offset: FixedOffset,
564 pub today: NaiveDate,
565 pub my_user_id: Option<String>,
566 pub names: HashMap<String, String>,
567 pub pending_reactions: PendingReactions,
568 pub card_overrides: HashMap<String, CardOverride>,
569 pub translation: TranslationContext,
570 pub skin_tone: u8,
571}
572
573fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {
574 let mut visible = reactions(record);
575 apply_pending_reactions(
576 &mut visible,
577 context.pending_reactions.get(&record.message_id),
578 context.my_user_id.as_deref(),
579 Utc::now(),
580 );
581 visible
582}
583
584pub fn call_card(event: &CallEvent, time: &str, my_user_id: Option<&str>) -> CallCard {
585 let missed = event.missed(my_user_id);
586 let detail = match (event.phase, event.duration_seconds) {
587 (CallPhase::Ended, Some(seconds)) if !missed => {
588 format!("{} \u{b7} {time}", format_duration(seconds))
589 }
590 _ => time.to_owned(),
591 };
592 CallCard {
593 title: event.title(missed),
594 detail,
595 icon: match (missed, event.call_type) {
596 (true, _) => CallIcon::Missed,
597 (false, CallType::Meeting) => CallIcon::Video,
598 (false, CallType::Call) => CallIcon::Call,
599 },
600 missed,
601 started: event.phase == CallPhase::Started,
602 }
603}
604
605fn call_row(record: &MessageRecord, event: &CallEvent, context: &RowContext) -> MessageRow {
606 let my_user_id = context.my_user_id.as_deref();
607 let time = clock_label(record.created_at, context.offset);
608 let author = event
609 .initiator_name
610 .clone()
611 .or_else(|| {
612 event
613 .initiator_id
614 .as_ref()
615 .and_then(|user_id| context.names.get(user_id).cloned())
616 })
617 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
618 MessageRow {
619 key: record.message_id.clone(),
620 conversation_id: record.conversation_id.clone(),
621 sender_id: event.initiator_id.clone(),
622 application_id: None,
623 created_at: record.created_at,
624 series: Series::default(),
625 author,
626 day_header: Some(format::day_label(
627 record
628 .created_at
629 .with_timezone(&context.offset)
630 .date_naive(),
631 context.today,
632 )),
633 blocks: Vec::new(),
634 jumbo: None,
635 edited: false,
636 deleted: false,
637 reactions: Vec::new(),
638 images: Vec::new(),
639 local_images: Vec::new(),
640 files: Vec::new(),
641 link_preview: None,
642 meeting_link: None,
643 adaptive_cards: Vec::new(),
644 subject: None,
645 new_marker: false,
646 reply_root: None,
647 delivery: Delivery::Delivered,
648 receipt: Receipt::Hidden,
649 own: event.initiated_by(my_user_id),
650 forwarded: false,
651 translation: None,
652 call: Some(call_card(event, &time, my_user_id)),
653 time,
654 }
655}
656
657const QUOTE_LINES: usize = 5;
658
659pub fn quoted_texts(records: &[MessageRecord]) -> HashMap<String, String> {
660 let wanted: std::collections::HashSet<String> = records
661 .iter()
662 .flat_map(quotes)
663 .map(|quote| quote.message_id)
664 .collect();
665 records
666 .iter()
667 .filter(|record| !record.deleted && wanted.contains(&record.message_id))
668 .map(|record| {
669 let text = readable_text(record);
670 let lines: Vec<&str> = text.lines().filter(|line| !line.trim().is_empty()).collect();
671 let mut shown = lines.iter().take(QUOTE_LINES).copied().collect::<Vec<_>>().join("\n");
672 if lines.len() > QUOTE_LINES {
673 shown.push_str(" …");
674 }
675 (record.message_id.clone(), shown)
676 })
677 .collect()
678}
679
680pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
681 message_row_with(record, context, &HashMap::new())
682}
683
684fn message_row_with(
685 record: &MessageRecord,
686 context: &RowContext,
687 quoted: &HashMap<String, String>,
688) -> MessageRow {
689 if let Some(event) = call_event(record) {
690 return call_row(record, &event, context);
691 }
692 let local = record.created_at.with_timezone(&context.offset);
693 let images = images(record);
694 let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id;
695 let translation = context.translation.resolve(record, own);
696 let blocks = if record.deleted {
697 vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]
698 } else if let Some(html) = &translation.translated_html {
699 layout_blocks(&translated_spans(record, html))
700 } else {
701 layout_blocks(&linked_message_spans_with(record, &|id| quoted.get(id).cloned()))
702 };
703 let blocks = if images.is_empty() {
704 blocks
705 } else {
706 strip_image_placeholders(blocks)
707 };
708 MessageRow {
709 key: record.message_id.clone(),
710 conversation_id: record.conversation_id.clone(),
711 sender_id: record.sender_id.clone(),
712 application_id: record.sender_application_id.clone(),
713 created_at: record.created_at,
714 series: Series::default(),
715 author: record
716 .sender_name
717 .clone()
718 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
719 time: clock_label(record.created_at, context.offset),
720 day_header: Some(format::day_label(local.date_naive(), context.today)),
721 blocks,
722 jumbo: (!record.deleted && !is_forwarded(&record.body_html))
723 .then(|| jumbo_emoji(&record.body_html))
724 .flatten(),
725 edited: record.edited_at.is_some() && !record.deleted,
726 deleted: record.deleted,
727 reactions: reaction_chips(&visible_reactions(record, context), context),
728 images,
729 local_images: Vec::new(),
730 files: files(record),
731 link_preview: link_preview(record),
732 meeting_link: (!record.deleted)
733 .then(|| meeting_link_in_html(&record.body_html))
734 .flatten(),
735 adaptive_cards: match context.card_overrides.get(&record.message_id) {
736 Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
737 _ => adaptive_cards(record),
738 },
739 subject: record.subject.clone(),
740 new_marker: false,
741 reply_root: record.reply_to_id.clone(),
742 delivery: Delivery::Delivered,
743 receipt: Receipt::Hidden,
744 own,
745 forwarded: !record.deleted && is_forwarded(&record.body_html),
746 translation: translation.line,
747 call: None,
748 }
749}
750
751pub fn is_forwarded(body_html: &str) -> bool {
752 body_html.contains(FORWARD_ITEMTYPE)
753}
754
755fn finished_call_ids(events: &[Option<CallEvent>]) -> HashSet<&str> {
756 events
757 .iter()
758 .flatten()
759 .filter(|event| event.phase == CallPhase::Ended)
760 .map(|event| event.call_id.as_str())
761 .collect()
762}
763
764fn is_open_start(event: &CallEvent, finished: &HashSet<&str>) -> bool {
765 event.phase == CallPhase::Started && !finished.contains(event.call_id.as_str())
766}
767
768pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {
769 let mut rows = Vec::with_capacity(records.len() + 1);
770 if has_older {
771 rows.push(Row::LoadOlder);
772 }
773 let events: Vec<Option<CallEvent>> = records.iter().map(call_event).collect();
774 let finished = finished_call_ids(&events);
775 let newest_open_start = events.iter().rposition(|event| {
776 event
777 .as_ref()
778 .is_some_and(|event| is_open_start(event, &finished))
779 });
780 let mut previous_day: Option<NaiveDate> = None;
781 let quoted = quoted_texts(records);
782 for (index, (record, event)) in records.iter().zip(&events).enumerate() {
783 let mut row = match event {
784 Some(event)
785 if event.phase == CallPhase::Started && !is_open_start(event, &finished) =>
786 {
787 continue;
788 }
789 Some(event) => call_row(record, event, context),
790 None => message_row_with(record, context, &quoted),
791 };
792 if let Some(call) = row.call.as_mut() {
793 call.started &= newest_open_start == Some(index);
794 }
795 let day = record
796 .created_at
797 .with_timezone(&context.offset)
798 .date_naive();
799 if previous_day == Some(day) {
800 row.day_header = None;
801 }
802 previous_day = Some(day);
803 rows.push(Row::Message(Box::new(row)));
804 }
805 assign_series(&mut rows);
806 rows
807}
808
809pub fn group_threads(records: &[MessageRecord]) -> Vec<Thread> {
810 let mut threads: Vec<Thread> = Vec::new();
811 let mut index_by_root: BTreeMap<&str, usize> = BTreeMap::new();
812 for record in records.iter().filter(|record| record.reply_to_id.is_none()) {
813 index_by_root.insert(record.message_id.as_str(), threads.len());
814 threads.push(Thread {
815 root_id: record.message_id.clone(),
816 reply_ids: Vec::new(),
817 });
818 }
819 for record in records {
820 let Some(root_id) = record.reply_to_id.as_deref() else {
821 continue;
822 };
823 if let Some(&index) = index_by_root.get(root_id) {
824 threads[index].reply_ids.push(record.message_id.clone());
825 }
826 }
827 threads
828}
829
830fn last_activity(thread: &Thread, by_id: &BTreeMap<&str, &MessageRecord>) -> DateTime<Utc> {
831 thread
832 .reply_ids
833 .iter()
834 .chain(std::iter::once(&thread.root_id))
835 .filter_map(|id| by_id.get(id.as_str()))
836 .map(|record| record.created_at)
837 .max()
838 .unwrap_or_default()
839}
840
841fn post_message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
842 let mut row = message_row(record, context);
843 row.day_header = None;
844 row.time = format::post_time_label(record.created_at, context.today, context.offset);
845 row
846}
847
848fn distinct_names<'a>(records: impl Iterator<Item = &'a MessageRecord>) -> Vec<String> {
849 let mut names: Vec<String> = Vec::new();
850 for record in records {
851 let name = record
852 .sender_name
853 .clone()
854 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
855 if !names.contains(&name) {
856 names.push(name);
857 }
858 }
859 names
860}
861
862fn post_row(
863 root: &MessageRecord,
864 mut replies: Vec<&MessageRecord>,
865 context: &RowContext,
866) -> PostRow {
867 replies.sort_by_key(|reply| reply.created_at);
868 let hidden = replies.len().saturating_sub(POST_VISIBLE_REPLIES);
869 PostRow {
870 root: post_message_row(root, context),
871 hidden_reply_count: hidden,
872 hidden_repliers: distinct_names(replies[..hidden].iter().copied()),
873 replies: replies[hidden..]
874 .iter()
875 .map(|reply| post_message_row(reply, context))
876 .collect(),
877 }
878}
879
880pub fn thread_list_rows(
881 records: &[MessageRecord],
882 context: &RowContext,
883 has_older: bool,
884) -> Vec<Row> {
885 let by_id: BTreeMap<&str, &MessageRecord> = records
886 .iter()
887 .filter(|record| record.call_event_json.is_none())
888 .map(|record| (record.message_id.as_str(), record))
889 .collect();
890 let mut threads = group_threads(records);
891 threads.sort_by_key(|thread| std::cmp::Reverse(last_activity(thread, &by_id)));
892 let mut rows: Vec<Row> = threads
893 .iter()
894 .filter_map(|thread| {
895 let root = by_id.get(thread.root_id.as_str())?;
896 let replies = thread
897 .reply_ids
898 .iter()
899 .filter_map(|id| by_id.get(id.as_str()).copied())
900 .collect();
901 Some(Row::Post(Box::new(post_row(root, replies, context))))
902 })
903 .collect();
904 if has_older {
905 rows.push(Row::LoadOlder);
906 }
907 rows
908}
909
910pub fn place_local_rows(rows: &mut Vec<Row>, local: Vec<MessageRow>) {
911 for message in local {
912 let Some(root_id) = message.reply_root.clone() else {
913 rows.insert(0, Row::Post(Box::new(PostRow::local(message))));
914 continue;
915 };
916 let position = rows
917 .iter()
918 .position(|row| matches!(row, Row::Post(post) if post.root.key == root_id));
919 if let Some(position) = position {
920 let mut row = rows.remove(position);
921 if let Row::Post(post) = &mut row {
922 post.replies.push(message);
923 }
924 rows.insert(0, row);
925 }
926 }
927}
928
929pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> {
930 let members: Vec<MessageRecord> = records
931 .iter()
932 .filter(|record| {
933 record.message_id == root_id || record.reply_to_id.as_deref() == Some(root_id)
934 })
935 .cloned()
936 .collect();
937 flat_rows(&members, context, false)
938}
939
940#[derive(Debug, Clone, PartialEq, Eq)]
941pub struct Splice {
942 pub range: Range<usize>,
943 pub count: usize,
944}
945
946pub fn diff_keys(old: &[String], new: &[String]) -> Option<Splice> {
947 if old == new {
948 return None;
949 }
950 let prefix = old
951 .iter()
952 .zip(new)
953 .take_while(|(left, right)| left == right)
954 .count();
955 let suffix = old[prefix..]
956 .iter()
957 .rev()
958 .zip(new[prefix..].iter().rev())
959 .take_while(|(left, right)| left == right)
960 .count();
961 Some(Splice {
962 range: prefix..old.len() - suffix,
963 count: new.len() - prefix - suffix,
964 })
965}
966
967pub fn changed_indices(old: &[Row], new: &[Row]) -> Vec<usize> {
968 let prefix = old
969 .iter()
970 .zip(new)
971 .take_while(|(left, right)| left.key() == right.key())
972 .count();
973 let suffix = old[prefix..]
974 .iter()
975 .rev()
976 .zip(new[prefix..].iter().rev())
977 .take_while(|(left, right)| left.key() == right.key())
978 .count();
979 let mut changed: Vec<usize> = (0..prefix)
980 .filter(|&index| old[index] != new[index])
981 .collect();
982 changed.extend((0..suffix).filter_map(|offset| {
983 let old_index = old.len() - 1 - offset;
984 let new_index = new.len() - 1 - offset;
985 (old[old_index] != new[new_index]).then_some(new_index)
986 }));
987 changed
988}
989
990#[cfg(test)]
991mod tests {
992 use chrono::TimeZone;
993
994 use super::*;
995
996 fn record(id: &str, reply_to: Option<&str>, hour: u32, day: u32) -> MessageRecord {
997 MessageRecord {
998 conversation_id: "c".into(),
999 message_id: id.into(),
1000 reply_to_id: reply_to.map(str::to_owned),
1001 sender_id: Some("u".into()),
1002 sender_name: Some("Author".into()),
1003 sender_application_id: None,
1004 links_json: "[]".to_owned(),
1005 created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),
1006 edited_at: None,
1007 deleted: false,
1008 body_html: format!("<p>text {id}</p>"),
1009 attachments_json: "[]".into(),
1010 reactions_json: "[]".into(),
1011 mentions_json: "[]".into(),
1012 subject: None,
1013 call_event_json: None,
1014 }
1015 }
1016
1017 #[test]
1018 fn a_quote_shows_the_lines_of_the_quoted_message_when_it_is_loaded() {
1019 let mut quoted = record("q1", None, 8, 6);
1020 quoted.body_html = "<p>first link</p><p>second link</p>".into();
1021 let mut answer = record("a1", None, 9, 6);
1022 answer.body_html = "<attachment id=\"q1\"></attachment><p>please again</p>".into();
1023 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();
1024 let rows = flat_rows(&[quoted, answer], &context(), false);
1025 let reply = rows
1026 .iter()
1027 .find_map(|row| match row {
1028 Row::Message(row) if row.key == "a1" => Some(row.blocks.clone()),
1029 _ => None,
1030 })
1031 .unwrap();
1032 let Some(Block::Reply { children, .. }) = reply.first() else { panic!("{reply:?}") };
1033 let text = format!("{children:?}");
1034 assert!(text.contains(r"first link\nsecond link"), "{text}");
1035 }
1036
1037 fn own_reaction(reaction_type: &str) -> ReactionInfo {
1038 ReactionInfo {
1039 reaction_type: reaction_type.into(),
1040 user_id: Some("me".into()),
1041 user_name: None,
1042 created_at: None,
1043 }
1044 }
1045
1046 #[test]
1047 fn setting_a_reaction_is_idempotent_and_only_touches_mine() {
1048 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
1049 let other = ReactionInfo {
1050 user_id: Some("them".into()),
1051 ..own_reaction("like")
1052 };
1053 let mut reactions = vec![other.clone()];
1054 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now);
1055 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now);
1056 assert_eq!(reactions.len(), 2);
1057 assert_eq!(reactions[1].reaction_type, "like");
1058 assert_eq!(reactions[1].user_id.as_deref(), Some("me"));
1059 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now);
1060 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now);
1061 assert_eq!(reactions, vec![other]);
1062 }
1063
1064 #[test]
1065 fn setting_matches_legacy_names_and_variation_selectors() {
1066 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
1067 let mut reactions = vec![own_reaction("heart")];
1068 assert!(has_own_reaction(&reactions, "\u{2764}\u{FE0F}", Some("me")));
1069 set_own_reaction(&mut reactions, "\u{2764}\u{FE0F}", Some("me"), false, now);
1070 assert!(reactions.is_empty());
1071 set_own_reaction(&mut reactions, "\u{1F389}", Some("me"), true, now);
1072 assert_eq!(reactions[0].reaction_type, "\u{1F389}");
1073 }
1074
1075 #[test]
1076 fn setting_without_a_known_user_never_matches() {
1077 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
1078 let mut reactions = Vec::new();
1079 set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now);
1080 set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now);
1081 assert_eq!(reactions.len(), 2);
1082 }
1083
1084 #[test]
1085 fn pending_reactions_overlay_the_stored_ones() {
1086 let mut stored = record("a", None, 8, 6);
1087 stored.reactions_json = serde_json::to_string(&[own_reaction("like")]).unwrap();
1088 let mut context = context();
1089 context.my_user_id = Some("me".into());
1090 context.pending_reactions.insert(
1091 "a".into(),
1092 vec![("\u{1F44D}".into(), false), ("\u{1F389}".into(), true)],
1093 );
1094 let chips = message_row(&stored, &context).reactions;
1095 assert_eq!(chips.len(), 1);
1096 assert_eq!(chips[0].reaction_type, "\u{1F389}");
1097 assert!(chips[0].mine);
1098 }
1099
1100 #[test]
1101 fn reaction_type_maps_classic_glyphs_to_names() {
1102 assert_eq!(reaction_type_for("\u{1F44D}"), "like");
1103 assert_eq!(reaction_type_for("\u{2764}\u{FE0F}"), "heart");
1104 assert_eq!(reaction_type_for("\u{1F389}"), "\u{1F389}");
1105 assert_eq!(reaction_glyph("like"), reaction_glyph("\u{1F44D}"));
1106 assert_eq!(reaction_glyph("heart"), reaction_glyph("\u{2764}\u{FE0F}"));
1107 assert_eq!(api_reaction(&reaction_glyph("heart")), "\u{2764}\u{FE0F}");
1108 assert_eq!(api_reaction(&reaction_glyph("like")), "\u{1F44D}");
1109 }
1110
1111 #[test]
1112 fn forwarded_messages_are_detected_by_the_forward_blockquote() {
1113 assert!(is_forwarded(
1114 r#"<p>fyi</p><blockquote itemscope="" itemtype="http://schema.skype.com/Forward" itemid="1">text</blockquote>"#
1115 ));
1116 assert!(!is_forwarded(
1117 r#"<blockquote itemtype="http://schema.skype.com/Reply">text</blockquote>"#
1118 ));
1119 assert!(!is_forwarded("<p>plain</p>"));
1120 let mut forwarded = record("f", None, 8, 6);
1121 forwarded.body_html =
1122 r#"<blockquote itemtype="http://schema.skype.com/Forward">text</blockquote>"#.into();
1123 assert!(message_row(&forwarded, &context()).forwarded);
1124 forwarded.deleted = true;
1125 assert!(!message_row(&forwarded, &context()).forwarded);
1126 }
1127
1128 #[test]
1129 fn editing_loads_the_message_formatted_without_its_reply_quote() {
1130 let mut edited = record("a", None, 8, 6);
1131 edited.body_html =
1132 "<blockquote itemtype=\"http://schema.skype.com/Reply\">old</blockquote>\
1133 <p><b>Plan</b> for <a href=\"https://x.test\">today</a></p>\
1134 <ol><li>one</li><li>two</li></ol>"
1135 .into();
1136 let draft = message_draft(&edited);
1137 assert_eq!(draft.text(), "Plan for today\n1. one\n2. two");
1138 assert_eq!(
1139 draft.to_html(),
1140 "<b>Plan</b> for <a href=\"https://x.test\">today</a><ol><li>one</li><li>two</li></ol>"
1141 );
1142 }
1143
1144 #[test]
1145 fn reply_excerpt_uses_the_first_line_or_the_attachment() {
1146 let mut text = record("a", None, 8, 6);
1147 text.body_html = "<p>first line</p><p>second</p>".into();
1148 assert_eq!(reply_excerpt(&text), "first line");
1149 let mut quoted = record("q", None, 8, 6);
1150 quoted.body_html = r#"<blockquote itemtype="http://schema.skype.com/Reply">Jonas<br>old text</blockquote><p>my answer</p>"#.into();
1151 assert_eq!(reply_excerpt(&quoted), "my answer");
1152 let mut image = record("b", None, 8, 6);
1153 image.body_html = "<img src=\"u\">".into();
1154 assert_eq!(reply_excerpt(&image), "Image");
1155 let mut long = record("c", None, 8, 6);
1156 long.body_html = format!("<p>{}</p>", "x".repeat(200));
1157 assert!(reply_excerpt(&long).ends_with("..."));
1158 assert_eq!(
1159 reply_excerpt(&long).chars().count(),
1160 REPLY_EXCERPT_CHARS + 3
1161 );
1162 }
1163
1164 fn context() -> RowContext {
1165 RowContext {
1166 offset: FixedOffset::east_opt(0).unwrap(),
1167 today: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(),
1168 my_user_id: None,
1169 names: HashMap::new(),
1170 pending_reactions: HashMap::new(),
1171 card_overrides: HashMap::new(),
1172 translation: TranslationContext::default(),
1173 skin_tone: 0,
1174 }
1175 }
1176
1177 fn keys(rows: &[Row]) -> Vec<String> {
1178 rows.iter().map(|row| row.key().to_owned()).collect()
1179 }
1180
1181 fn translation_context(shown: bool) -> RowContext {
1182 use crate::translation::CachedTranslation;
1183 let mut context = context();
1184 context.translation.enabled = true;
1185 context.translation.target = "en".into();
1186 context.translation.stamps.insert(
1187 "a".into(),
1188 "languages=fr:100;length:80;&detector=Bling".into(),
1189 );
1190 context.my_user_id = Some("me".into());
1191 if shown {
1192 context.translation.cached.insert(
1193 ("a".into(), 0),
1194 CachedTranslation {
1195 html: "<p><strong>translated</strong> body</p>".into(),
1196 source: Some("fr".into()),
1197 },
1198 );
1199 context.translation.shown.insert("a".into());
1200 }
1201 context
1202 }
1203
1204 #[test]
1205 fn a_foreign_message_carries_the_offer_and_keeps_its_text() {
1206 let row = message_row(&record("a", None, 8, 6), &translation_context(false));
1207 assert!(matches!(
1208 row.translation,
1209 Some(TranslationLine::Offer { ref language_code, .. }) if language_code == "fr"
1210 ));
1211 assert_eq!(
1212 row.blocks,
1213 layout_blocks(&teams_core::linked_message_spans(&record("a", None, 8, 6)))
1214 );
1215 }
1216
1217 #[test]
1218 fn a_shown_translation_replaces_the_body_and_the_original_comes_back() {
1219 let original = message_row(&record("a", None, 8, 6), &translation_context(false)).blocks;
1220 let translated = message_row(&record("a", None, 8, 6), &translation_context(true));
1221 assert_ne!(translated.blocks, original);
1222 assert_eq!(
1223 translated.translation,
1224 Some(TranslationLine::Translated {
1225 language: Some("French".into()),
1226 showing_original: false
1227 })
1228 );
1229 let mut hidden = translation_context(true);
1230 hidden.translation.shown.clear();
1231 let back = message_row(&record("a", None, 8, 6), &hidden);
1232 assert_eq!(back.blocks, original);
1233 assert_eq!(
1234 back.translation,
1235 Some(TranslationLine::Translated {
1236 language: Some("French".into()),
1237 showing_original: true
1238 })
1239 );
1240 }
1241
1242 #[test]
1243 fn own_messages_get_no_offer() {
1244 let mut own = record("a", None, 8, 6);
1245 own.sender_id = Some("me".into());
1246 assert_eq!(
1247 message_row(&own, &translation_context(false)).translation,
1248 None
1249 );
1250 }
1251
1252 #[test]
1253 fn day_header_only_on_first_message_of_a_day() {
1254 let records = vec![
1255 record("a", None, 8, 6),
1256 record("b", None, 9, 6),
1257 record("c", None, 9, 7),
1258 ];
1259 let rows = flat_rows(&records, &context(), false);
1260 let headers: Vec<Option<String>> = rows
1261 .iter()
1262 .map(|row| match row {
1263 Row::Message(message) => message.day_header.clone(),
1264 Row::LoadOlder
1265 | Row::LoadNewer
1266 | Row::Start(_)
1267 | Row::Skeleton(_)
1268 | Row::Post(_) => None,
1269 })
1270 .collect();
1271 assert_eq!(
1272 headers,
1273 vec![Some("Yesterday".into()), None, Some("Today".into())]
1274 );
1275 }
1276
1277 #[test]
1278 fn load_older_row_only_when_more_exists() {
1279 let records = vec![record("a", None, 8, 6)];
1280 assert_eq!(
1281 keys(&flat_rows(&records, &context(), true))[0],
1282 LOAD_OLDER_KEY
1283 );
1284 assert_eq!(keys(&flat_rows(&records, &context(), false)), vec!["a"]);
1285 }
1286
1287 #[test]
1288 fn threads_group_replies_by_root() {
1289 let records = vec![
1290 record("r1", None, 8, 6),
1291 record("r2", None, 9, 6),
1292 record("x1", Some("r1"), 10, 6),
1293 record("x2", Some("r1"), 11, 6),
1294 record("orphan", Some("missing"), 12, 6),
1295 ];
1296 let threads = group_threads(&records);
1297 assert_eq!(threads.len(), 2);
1298 assert_eq!(threads[0].reply_ids, vec!["x1", "x2"]);
1299 assert!(threads[1].reply_ids.is_empty());
1300 }
1301
1302 fn post_of(row: &Row) -> &PostRow {
1303 let Row::Post(post) = row else {
1304 panic!("post expected")
1305 };
1306 post
1307 }
1308
1309 fn reply_by(id: &str, root: &str, sender: &str, hour: u32) -> MessageRecord {
1310 let mut reply = record(id, Some(root), hour, 6);
1311 reply.sender_name = Some(sender.into());
1312 reply
1313 }
1314
1315 #[test]
1316 fn feed_orders_posts_by_last_activity_newest_first() {
1317 let records = vec![
1318 record("r1", None, 8, 6),
1319 record("r2", None, 9, 6),
1320 record("r3", None, 10, 6),
1321 record("x1", Some("r1"), 11, 6),
1322 ];
1323 let rows = thread_list_rows(&records, &context(), false);
1324 assert_eq!(keys(&rows), vec!["r1", "r3", "r2"]);
1325 }
1326
1327 #[test]
1328 fn feed_puts_load_older_at_the_bottom() {
1329 let records = vec![record("r1", None, 8, 6), record("r2", None, 9, 6)];
1330 let rows = thread_list_rows(&records, &context(), true);
1331 assert_eq!(keys(&rows), vec!["r2", "r1", LOAD_OLDER_KEY]);
1332 }
1333
1334 #[test]
1335 fn post_shows_the_last_three_replies_oldest_first() {
1336 let mut records = vec![record("r1", None, 1, 6)];
1337 for hour in 2..=6 {
1338 records.push(reply_by(&format!("x{hour}"), "r1", "Ada Lovelace", hour));
1339 }
1340 records.reverse();
1341 let rows = thread_list_rows(&records, &context(), false);
1342 let post = post_of(&rows[0]);
1343 let shown: Vec<&str> = post
1344 .replies
1345 .iter()
1346 .map(|reply| reply.key.as_str())
1347 .collect();
1348 assert_eq!(shown, vec!["x4", "x5", "x6"]);
1349 assert_eq!(post.hidden_reply_count, 2);
1350 assert_eq!(post.hidden_repliers, vec!["Ada Lovelace"]);
1351 }
1352
1353 #[test]
1354 fn post_without_hidden_replies_has_no_link() {
1355 let records = vec![
1356 record("r1", None, 1, 6),
1357 reply_by("x1", "r1", "Ada", 2),
1358 reply_by("x2", "r1", "Ben", 3),
1359 reply_by("x3", "r1", "Cy", 4),
1360 ];
1361 let rows = thread_list_rows(&records, &context(), false);
1362 assert_eq!(post_of(&rows[0]).hidden_replies_label(), None);
1363 assert_eq!(post_of(&rows[0]).replies.len(), 3);
1364 }
1365
1366 fn label_for(repliers: &[&str]) -> String {
1367 let mut records = vec![record("r1", None, 1, 6)];
1368 for (index, name) in repliers.iter().enumerate() {
1369 records.push(reply_by(&format!("h{index}"), "r1", name, 2 + index as u32));
1370 }
1371 for index in 0..POST_VISIBLE_REPLIES {
1372 records.push(reply_by(
1373 &format!("v{index}"),
1374 "r1",
1375 "Shown",
1376 20 + index as u32,
1377 ));
1378 }
1379 let rows = thread_list_rows(&records, &context(), false);
1380 post_of(&rows[0]).hidden_replies_label().unwrap()
1381 }
1382
1383 #[test]
1384 fn replies_label_names_one_to_three_people() {
1385 assert_eq!(label_for(&["Anna Meier"]), "1 reply from Anna");
1386 assert_eq!(
1387 label_for(&["Anna Meier", "Anna Meier", "Ben Roth"]),
1388 "3 replies from Anna and Ben"
1389 );
1390 assert_eq!(
1391 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Ben Roth"]),
1392 "4 replies from Anna, Ben and Clara"
1393 );
1394 }
1395
1396 #[test]
1397 fn replies_label_counts_the_others_beyond_three_people() {
1398 assert_eq!(
1399 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox", "Eve Ray"]),
1400 "5 replies from Anna, Ben and 3 others"
1401 );
1402 assert_eq!(
1403 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox"]),
1404 "4 replies from Anna, Ben and 2 others"
1405 );
1406 }
1407
1408 #[test]
1409 fn local_reply_lands_in_its_post_and_local_post_on_top() {
1410 let records = vec![
1411 record("r1", None, 8, 6),
1412 record("r2", None, 9, 6),
1413 reply_by("x1", "r1", "Ada", 10),
1414 ];
1415 let mut rows = thread_list_rows(&records, &context(), true);
1416 let mut pending_reply = message_row(&record("pending-1", Some("r2"), 12, 6), &context());
1417 pending_reply.reply_root = Some("r2".into());
1418 let pending_post = message_row(&record("pending-2", None, 12, 6), &context());
1419 place_local_rows(&mut rows, vec![pending_reply, pending_post]);
1420 assert_eq!(keys(&rows), vec!["pending-2", "r2", "r1", LOAD_OLDER_KEY]);
1421 let replies: Vec<&str> = post_of(&rows[1])
1422 .replies
1423 .iter()
1424 .map(|reply| reply.key.as_str())
1425 .collect();
1426 assert_eq!(replies, vec!["pending-1"]);
1427 }
1428
1429 #[test]
1430 fn local_reply_to_an_unloaded_post_is_not_shown() {
1431 let mut rows = thread_list_rows(&[record("r1", None, 8, 6)], &context(), false);
1432 let mut orphan = message_row(&record("pending-1", Some("gone"), 12, 6), &context());
1433 orphan.reply_root = Some("gone".into());
1434 place_local_rows(&mut rows, vec![orphan]);
1435 assert_eq!(keys(&rows), vec!["r1"]);
1436 }
1437
1438 #[test]
1439 fn subject_reaches_the_post_root() {
1440 let mut with_subject = record("r1", None, 8, 6);
1441 with_subject.subject = Some("Release plan".into());
1442 let rows = thread_list_rows(&[with_subject, record("r2", None, 7, 6)], &context(), false);
1443 assert_eq!(
1444 post_of(&rows[0]).root.subject.as_deref(),
1445 Some("Release plan")
1446 );
1447 assert_eq!(post_of(&rows[1]).root.subject, None);
1448 }
1449
1450 #[test]
1451 fn thread_view_has_root_then_replies() {
1452 let records = vec![
1453 record("r1", None, 8, 6),
1454 record("r2", None, 9, 6),
1455 record("x1", Some("r1"), 10, 6),
1456 ];
1457 assert_eq!(
1458 keys(&thread_rows(&records, "r1", &context())),
1459 vec!["r1", "x1"]
1460 );
1461 }
1462
1463 #[test]
1464 fn reactions_are_counted_in_first_seen_order() {
1465 let reaction = |kind: &str| ReactionInfo {
1466 reaction_type: kind.into(),
1467 user_id: None,
1468 user_name: None,
1469 created_at: None,
1470 };
1471 let chips = reaction_chips(
1472 &[reaction("heart"), reaction("like"), reaction("heart")],
1473 &context(),
1474 );
1475 assert_eq!(chips.len(), 2);
1476 assert_eq!(chips[0].count, 2);
1477 assert_eq!(chips[1].label, reaction_label("like"));
1478 }
1479
1480 #[test]
1481 fn legacy_laugh_and_sad_use_the_teams_glyphs() {
1482 assert_eq!(reaction_label("laugh"), "\u{1F606}");
1483 assert_eq!(reaction_label("sad"), "\u{1F641}");
1484 assert_eq!(reaction_type_for("\u{1F606}"), "laugh");
1485 assert_eq!(reaction_type_for("\u{1F641}"), "sad");
1486 }
1487
1488 #[test]
1489 fn legacy_and_emoji_reactions_share_a_chip() {
1490 let reaction = |kind: &str| ReactionInfo {
1491 reaction_type: kind.into(),
1492 user_id: None,
1493 user_name: Some("Lea".into()),
1494 created_at: None,
1495 };
1496 let chips = reaction_chips(&[reaction("like"), reaction("\u{1F44D}")], &context());
1497 assert_eq!(chips.len(), 1);
1498 assert_eq!(chips[0].count, 2);
1499 }
1500
1501 #[test]
1502 fn skin_tones_share_a_chip_showing_up_to_three_variants() {
1503 let reaction = |kind: &str| ReactionInfo {
1504 reaction_type: kind.into(),
1505 user_id: Some(kind.into()),
1506 user_name: Some("Lea".into()),
1507 created_at: None,
1508 };
1509 let kinds = ["yes-tone2", "👍🏿", "like", "👍🏻", "yes-tone2"];
1510 let mut context = context();
1511 context.skin_tone = 3;
1512 let chips = reaction_chips(&kinds.map(reaction), &context);
1513 assert_eq!(chips.len(), 1);
1514 assert_eq!(chips[0].count, 5);
1515 assert_eq!(chips[0].label, "👍🏼👍🏿👍");
1516 assert_eq!(chips[0].click_glyph, "👍🏽");
1517 }
1518
1519 #[test]
1520 fn own_toned_reaction_matches_the_plain_glyph() {
1521 let mine = ReactionInfo {
1522 reaction_type: "👍🏼".into(),
1523 user_id: Some("me".into()),
1524 user_name: None,
1525 created_at: None,
1526 };
1527 let reactions = vec![mine];
1528 assert!(has_own_reaction(&reactions, "\u{1F44D}", Some("me")));
1529 assert_eq!(
1530 own_reaction_glyph(&reactions, "like", Some("me")).as_deref(),
1531 Some("👍🏼")
1532 );
1533 assert_eq!(reaction_glyph("yes-tone5"), "👍🏿");
1534 }
1535
1536 #[test]
1537 fn reactor_name_falls_back_to_directory_then_unknown() {
1538 let reaction = |user: &str| ReactionInfo {
1539 reaction_type: "like".into(),
1540 user_id: Some(user.into()),
1541 user_name: None,
1542 created_at: None,
1543 };
1544 let mut context = context();
1545 context.names.insert("known".into(), "Priya Nair".into());
1546 let chips = reaction_chips(&[reaction("known"), reaction("other")], &context);
1547 assert_eq!(chips[0].reactors[0].name, "Priya Nair");
1548 assert_eq!(chips[0].reactors[1].name, "Unknown");
1549 }
1550
1551 fn record_by(id: &str, sender: &str, hour: u32, minute: u32, day: u32) -> MessageRecord {
1552 let mut record = record(id, None, hour, day);
1553 record.sender_id = Some(sender.into());
1554 record.created_at = Utc
1555 .with_ymd_and_hms(2026, 10, day, hour, minute, 0)
1556 .unwrap();
1557 record
1558 }
1559
1560 fn series_of(rows: &[Row]) -> Vec<(bool, bool)> {
1561 rows.iter()
1562 .filter_map(|row| match row {
1563 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
1564 Row::LoadOlder
1565 | Row::LoadNewer
1566 | Row::Start(_)
1567 | Row::Skeleton(_)
1568 | Row::Post(_) => None,
1569 })
1570 .collect()
1571 }
1572
1573 #[test]
1574 fn series_joins_same_sender_within_five_minutes() {
1575 let records = vec![
1576 record_by("a", "ada", 9, 0, 7),
1577 record_by("b", "ada", 9, 4, 7),
1578 record_by("c", "ada", 9, 20, 7),
1579 record_by("d", "bob", 9, 21, 7),
1580 record_by("e", "ada", 9, 22, 7),
1581 ];
1582 let rows = flat_rows(&records, &context(), false);
1583 assert_eq!(
1584 series_of(&rows),
1585 vec![
1586 (false, true),
1587 (true, false),
1588 (false, false),
1589 (false, false),
1590 (false, false)
1591 ]
1592 );
1593 }
1594
1595 #[test]
1596 fn series_window_ends_exactly_at_the_gap_constant() {
1597 let gap = SERIES_GAP_MINUTES as u32;
1598 let records = vec![
1599 record_by("a", "ada", 9, 0, 7),
1600 record_by("b", "ada", 9, gap - 1, 7),
1601 record_by("c", "ada", 9, 2 * gap - 1 + gap, 7),
1602 ];
1603 let rows = flat_rows(&records, &context(), false);
1604 assert_eq!(
1605 series_of(&rows),
1606 vec![(false, true), (true, false), (false, false)]
1607 );
1608 }
1609
1610 #[test]
1611 fn series_breaks_at_a_new_day() {
1612 let records = vec![
1613 record_by("a", "ada", 23, 58, 6),
1614 record_by("b", "ada", 0, 1, 7),
1615 ];
1616 let rows = flat_rows(&records, &context(), false);
1617 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
1618 }
1619
1620 fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] {
1621 let corners = bubble_corners(own, Series { has_prev, has_next });
1622 [
1623 corners.top_left,
1624 corners.top_right,
1625 corners.bottom_right,
1626 corners.bottom_left,
1627 ]
1628 }
1629
1630 #[test]
1631 fn corners_match_the_mockup_for_other_senders() {
1632 assert_eq!(corners(false, false, false), [14., 14., 14., 14.]);
1633 assert_eq!(corners(false, false, true), [14., 14., 14., 4.]);
1634 assert_eq!(corners(false, true, true), [4., 14., 14., 4.]);
1635 assert_eq!(corners(false, true, false), [4., 14., 14., 14.]);
1636 }
1637
1638 #[test]
1639 fn corners_match_the_mockup_for_own_messages() {
1640 assert_eq!(corners(true, false, false), [14., 14., 14., 14.]);
1641 assert_eq!(corners(true, false, true), [14., 14., 4., 14.]);
1642 assert_eq!(corners(true, true, true), [14., 4., 4., 14.]);
1643 assert_eq!(corners(true, true, false), [14., 4., 14., 14.]);
1644 }
1645
1646 #[test]
1647 fn own_reaction_is_marked() {
1648 let reaction = |user: &str| ReactionInfo {
1649 reaction_type: "like".into(),
1650 user_id: Some(user.into()),
1651 user_name: None,
1652 created_at: None,
1653 };
1654 let mut context = context();
1655 context.my_user_id = Some("me".into());
1656 let chips = reaction_chips(&[reaction("x"), reaction("me")], &context);
1657 assert!(chips[0].mine);
1658 assert!(!reaction_chips(&[reaction("x")], &context)[0].mine);
1659 }
1660
1661 fn strings(values: &[&str]) -> Vec<String> {
1662 values.iter().map(|value| (*value).to_owned()).collect()
1663 }
1664
1665 #[test]
1666 fn diff_detects_append_prepend_and_replace() {
1667 let base = strings(&["a", "b"]);
1668 assert_eq!(diff_keys(&base, &base), None);
1669 assert_eq!(
1670 diff_keys(&base, &strings(&["a", "b", "c"])),
1671 Some(Splice {
1672 range: 2..2,
1673 count: 1
1674 })
1675 );
1676 assert_eq!(
1677 diff_keys(&base, &strings(&["x", "a", "b"])),
1678 Some(Splice {
1679 range: 0..0,
1680 count: 1
1681 })
1682 );
1683 assert_eq!(
1684 diff_keys(
1685 &strings(&["load-older", "a"]),
1686 &strings(&["load-older", "x", "y", "a"])
1687 ),
1688 Some(Splice {
1689 range: 1..1,
1690 count: 2
1691 })
1692 );
1693 assert_eq!(
1694 diff_keys(&strings(&["load-older", "a"]), &strings(&["a"])),
1695 Some(Splice {
1696 range: 0..1,
1697 count: 0
1698 })
1699 );
1700 assert_eq!(
1701 diff_keys(&base, &strings(&["x"])),
1702 Some(Splice {
1703 range: 0..2,
1704 count: 1
1705 })
1706 );
1707 }
1708
1709 #[test]
1710 fn changed_indices_find_edited_rows() {
1711 let old = flat_rows(
1712 &[record("a", None, 8, 6), record("b", None, 9, 6)],
1713 &context(),
1714 false,
1715 );
1716 let mut edited = record("b", None, 9, 6);
1717 edited.body_html = "<p>changed</p>".into();
1718 let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false);
1719 assert_eq!(changed_indices(&old, &new), vec![1]);
1720 }
1721
1722 fn call_record(id: &str, hour: u32, event: CallEvent) -> MessageRecord {
1723 MessageRecord {
1724 sender_id: None,
1725 sender_name: None,
1726 body_html: String::new(),
1727 call_event_json: Some(event.to_json()),
1728 ..record(id, None, hour, 7)
1729 }
1730 }
1731
1732 fn call_event_of(
1733 phase: CallPhase,
1734 call_id: &str,
1735 initiator: &str,
1736 seconds: Option<u64>,
1737 participants: &[&str],
1738 ) -> CallEvent {
1739 CallEvent {
1740 phase,
1741 call_type: CallType::Call,
1742 call_id: call_id.into(),
1743 duration_seconds: seconds,
1744 initiator_id: Some(initiator.into()),
1745 initiator_name: Some(format!("Name {initiator}")),
1746 participant_ids: participants.iter().map(|id| (*id).to_owned()).collect(),
1747 }
1748 }
1749
1750 fn call_context() -> RowContext {
1751 let mut context = context();
1752 context.my_user_id = Some("me".into());
1753 context
1754 }
1755
1756 fn call_of(row: &Row) -> &CallCard {
1757 let Row::Message(message) = row else {
1758 panic!("not a message row")
1759 };
1760 message.call.as_ref().expect("call row")
1761 }
1762
1763 #[test]
1764 fn started_call_is_hidden_when_the_same_call_ended() {
1765 let records = [
1766 call_record(
1767 "s1",
1768 9,
1769 call_event_of(CallPhase::Started, "one", "u", None, &[]),
1770 ),
1771 call_record(
1772 "e1",
1773 10,
1774 call_event_of(CallPhase::Ended, "one", "u", Some(723), &["u", "me"]),
1775 ),
1776 call_record(
1777 "s2",
1778 11,
1779 call_event_of(CallPhase::Started, "two", "u", None, &[]),
1780 ),
1781 ];
1782 let rows = flat_rows(&records, &call_context(), false);
1783 assert_eq!(keys(&rows), ["e1", "s2"]);
1784 assert_eq!(call_of(&rows[0]).title, "Call ended");
1785 assert_eq!(call_of(&rows[0]).detail, "12m 3s \u{b7} 10:00");
1786 assert_eq!(call_of(&rows[1]).title, "Call started");
1787 assert_eq!(call_of(&rows[1]).detail, "11:00");
1788 assert!(call_of(&rows[1]).started);
1789 }
1790
1791 #[test]
1792 fn only_the_newest_open_start_can_be_joined() {
1793 let records = [
1794 call_record(
1795 "old",
1796 9,
1797 call_event_of(CallPhase::Started, "lost", "u", None, &[]),
1798 ),
1799 call_record(
1800 "new",
1801 11,
1802 call_event_of(CallPhase::Started, "live", "u", None, &[]),
1803 ),
1804 ];
1805 let rows = flat_rows(&records, &call_context(), false);
1806 assert_eq!(keys(&rows), ["old", "new"]);
1807 assert!(!call_of(&rows[0]).started);
1808 assert!(call_of(&rows[1]).started);
1809 }
1810
1811 #[test]
1812 fn missed_call_needs_an_incoming_call_with_fewer_than_two_participants() {
1813 let rows = flat_rows(
1814 &[
1815 call_record(
1816 "incoming",
1817 9,
1818 call_event_of(CallPhase::Ended, "a", "u", Some(60), &["u"]),
1819 ),
1820 call_record(
1821 "outgoing",
1822 10,
1823 call_event_of(CallPhase::Ended, "b", "me", Some(60), &["me"]),
1824 ),
1825 call_record(
1826 "answered",
1827 11,
1828 call_event_of(CallPhase::Ended, "c", "u", Some(60), &["u", "me"]),
1829 ),
1830 ],
1831 &call_context(),
1832 false,
1833 );
1834 let missed = call_of(&rows[0]);
1835 assert!(missed.missed);
1836 assert_eq!(missed.title, "Missed call");
1837 assert_eq!(missed.detail, "09:00");
1838 assert_eq!(missed.icon, CallIcon::Missed);
1839 let outgoing = call_of(&rows[1]);
1840 assert!(!outgoing.missed);
1841 assert_eq!(outgoing.title, "Call ended");
1842 assert_eq!(outgoing.detail, "1m \u{b7} 10:00");
1843 assert!(!call_of(&rows[2]).missed);
1844 }
1845
1846 #[test]
1847 fn call_side_follows_the_initiator() {
1848 let rows = flat_rows(
1849 &[
1850 call_record(
1851 "mine",
1852 9,
1853 call_event_of(CallPhase::Ended, "a", "me", Some(5), &["me", "u"]),
1854 ),
1855 call_record(
1856 "theirs",
1857 10,
1858 call_event_of(CallPhase::Ended, "b", "u", Some(5), &["me", "u"]),
1859 ),
1860 ],
1861 &call_context(),
1862 false,
1863 );
1864 let sides: Vec<(bool, Option<&str>)> = rows
1865 .iter()
1866 .map(|row| match row {
1867 Row::Message(message) => (message.own, message.sender_id.as_deref()),
1868 _ => unreachable!(),
1869 })
1870 .collect();
1871 assert_eq!(sides, [(true, Some("me")), (false, Some("u"))]);
1872 }
1873
1874 #[test]
1875 fn meeting_events_use_the_video_icon_and_meeting_titles() {
1876 let mut event = call_event_of(CallPhase::Ended, "m", "u", Some(3723), &["u", "me", "x"]);
1877 event.call_type = CallType::Meeting;
1878 let rows = flat_rows(&[call_record("m", 9, event)], &call_context(), false);
1879 let card = call_of(&rows[0]);
1880 assert_eq!(card.title, "Meeting ended");
1881 assert_eq!(card.icon, CallIcon::Video);
1882 assert_eq!(card.detail, "1h 2m 3s \u{b7} 09:00");
1883 }
1884
1885 #[test]
1886 fn call_rows_never_join_a_series() {
1887 let mut records = vec![
1888 record_by("a", "u", 9, 0, 7),
1889 call_record(
1890 "c",
1891 9,
1892 call_event_of(CallPhase::Ended, "x", "u", Some(5), &["u", "me"]),
1893 ),
1894 ];
1895 records.push(record_by("b", "u", 9, 1, 7));
1896 let rows = flat_rows(&records, &call_context(), false);
1897 let series: Vec<Series> = rows
1898 .iter()
1899 .map(|row| match row {
1900 Row::Message(message) => message.series,
1901 _ => unreachable!(),
1902 })
1903 .collect();
1904 assert!(series.iter().all(|series| *series == Series::default()));
1905 }
1906
1907 #[test]
1908 fn thread_lists_leave_call_events_out() {
1909 let records = [call_record(
1910 "c",
1911 9,
1912 call_event_of(CallPhase::Ended, "x", "u", Some(5), &["u", "me"]),
1913 )];
1914 assert!(thread_list_rows(&records, &call_context(), false).is_empty());
1915 }
1916}