BlueGit

ict rusty-teams

Files

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

rows.rs

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