BlueGit

ict rusty-teams

Files

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

rows.rs

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