BlueGit

ict rusty-teams

Files

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

rows.rs

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