BlueGit

ict rusty-teams

Files

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

rows.rs

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